[英]Create dictionary with multiple values per key
How can I create a dictionary with multiple values per key from 2 lists? 如何从2个列表中为每个键创建一个包含多个值的字典?
For example, I have: 例如,我有:
>>> list1 = ['fruit', 'fruit', 'vegetable']
>>> list2 = ['apple', 'banana', 'carrot']
And, I want something to the effect of: 而且,我想要一些效果:
>>> dictionary = {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
I have tried the following so far: 到目前为止,我已尝试过以下内容:
>>> keys = list1
>>> values = list2
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'fruit': 'banana', 'vegetable': 'carrot'}
You can use dict.setdefault
and a simple for-loop: 你可以使用
dict.setdefault
和一个简单的for循环:
>>> list1 = ["fruit", "fruit", "vegetable"]
>>> list2 = ["apple", "banana", "carrot"]
>>> dct = {}
>>> for i, j in zip(list1, list2):
... dct.setdefault(i, []).append(j)
...
>>> dct
{'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
setdefault(key[, default])
If
key
is in the dictionary, return its value.如果
key
在字典中,则返回其值。 If not, insertkey
with a value ofdefault
and returndefault
.如果没有,插入
key
,值为default
和返回default
。default
defaults toNone
.default
默认为None
。
You can use collections.defaultdict for such tasks : 您可以使用collections.defaultdict执行此类任务:
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for i,j in zip(list1,list2):
... d[i].append(j)
...
>>> d
defaultdict(<type 'list'>, {'vegetable': ['carrot'], 'fruit': ['apple', 'banana']})
This is a bit different from the other answers. 这与其他答案略有不同。 It is a bit simpler for beginners.
这对初学者来说有点简单。
list1 = ['fruit', 'fruit', 'vegetable']
list2 = ['apple', 'banana', 'carrot']
dictionary = {}
for i in list1:
dictionary[i] = []
for i in range(0,len(list1)):
dictionary[list1[i]].append(list2[i])
It will return 它会回来
{'vegetable': ['carrot'], 'fruit': ['apple', 'banana']}
This code runs through list1
and makes each item in it a key for an empty list in dictionary
. 此代码通过
list1
运行,并使其中的每个项目成为dictionary
中空列表的键。 It then goes from 0-2 and appends each item in list2
to its appropriate category, so that index 0 in each match up, index 1 in each match up, and index 2 in each match up. 然后它从0-2开始并将
list2
每个项目附加到其相应的类别,以便每个匹配中的索引0匹配,每个匹配中的索引1和每个匹配中的索引2匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.