是否有可能从两个具有相同键的列表创建字典而不遍历整个数据集?
最小的例子:
keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]
# hoped for result:
dictionary = dict(???)
dictionary = {1 : [1,8], 2:[2,4], 3:[3,5], 4:[6], 5:[7]}
当使用 zip
时,插入的键值对会覆盖旧的:
dictionary = dict(zip(keys,values))
dictionary = {1: 8, 2: 4, 3: 5, 4: 6, 5: 7}
我也会对 Multidict 感到满意。
最佳答案
这是一种不需要 2 个 for 循环的方法
h = defaultdict(list)
for k, v in zip(keys, values):
h[k].append(v)
print(h)
# defaultdict(<class 'list'>, {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]})
print(dict(h))
# {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]}
关于python - 来自两个列表的字典,包括键的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038406/