我有两个列表,我想从中创建一个字典。但是我想为一个键存储多个值

I have two list and I want to create a dictionary from it . But I want to store multiple values for one key

我有两个列表如下

idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]

我用下面的代码来制作字典,但它忽略了一个值。我想用一个键存储多个值。

res = dict(zip(idx, newx))
print(res)

输出看起来像 {344: (260, 368), 590: (514, 245)} 但我希望输出是 {344: [(257, 381),(260, 368)], 590: [(514, 245)]}

使用默认字典:

from collections import defaultdict

idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]

# default to empty list
res = defaultdict(list)
for k, v in zip(idx, newx):
    res[k].append(v)

# get rid of default value
res = dict(res)

您不能这样做,因为 dict 对象具有唯一键。你应该只使用元组列表:

idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]

res = zip(idx, newx)
print(list(res))

如果要访问基于键的所有值,请使用collections.defaultdict

我相信这会如你所愿。奖金,这不需要导入。

希望对您有所帮助。

res = {}
for k, v in zip(idx, newx):
    if k in res:
        res[k].append(v)
    else:
        res[k] = [v]