[英]I have two list and I want to create a dictionary from it . But I want to store multiple values for one key
I have two list as below我有两个列表如下
idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]
I used the below code to make dictionary but it neglected one value.我用下面的代码来制作字典,但它忽略了一个值。 I want to store multiple values with one key.
我想用一个键存储多个值。
res = dict(zip(idx, newx))
print(res)
output looks like {344: (260, 368), 590: (514, 245)}
but I want output to be {344: [(257, 381),(260, 368)], 590: [(514, 245)]}
output 看起来像
{344: (260, 368), 590: (514, 245)}
但我希望 output 是{344: [(257, 381),(260, 368)], 590: [(514, 245)]}
Use a defaultdict:使用默认字典:
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)
You can not do that as dict
objects have unique keys.您不能这样做,因为
dict
对象具有唯一键。 You should just the use list of tuple:你应该只使用元组列表:
idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]
res = zip(idx, newx)
print(list(res))
If you want to access all the values based on the key, use collections.defaultdict
如果要访问基于键的所有值,请使用
collections.defaultdict
I believe this will do what you want.我相信这会做你想做的。 Bonus, this won't require an import.
奖金,这不需要进口。
I hope this helps.我希望这有帮助。
res = {}
for k, v in zip(idx, newx):
if k in res:
res[k].append(v)
else:
res[k] = [v]
I have two list as below我有两个列表如下
idx = [344, 344, 590]
newx = [(257, 381), (260, 368), (514, 245)]
I used the below code to make dictionary but it neglected one value.我使用下面的代码制作字典,但它忽略了一个值。 I want to store multiple values with one key.
我想用一个键存储多个值。
res = dict(zip(idx, newx))
print(res)
output looks like {344: (260, 368), 590: (514, 245)}
but I want output to be {344: [(257, 381),(260, 368)], 590: [(514, 245)]}
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.