![](/img/trans.png)
[英]I have two lists one for x values and one for y values, I want to make a list from these
[英]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)
output 看起来像{344: (260, 368), 590: (514, 245)}
但我希望 output 是{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]
我有两个列表如下
idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]
我使用下面的代码制作字典,但它忽略了一个值。 我想用一个键存储多个值。
res = dict(zip(idx, newx))
print(res)
output 看起来像{344: (260, 368), 590: (514, 245)}
但我希望 output 是{344: [(257, 381),(260, 368)], 590: [(514, 245)]}
3148),(2960, (3), (2960, (3), 5 {344: [(257, 381),(260, 368)], 590: [(514, 245)]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.