如何从2个列表中为每个键创建一个包含多个值的字典?
例如,我有:
>>> list1 = ['fruit', 'fruit', 'vegetable']
>>> list2 = ['apple', 'banana', 'carrot']
Run Code Online (Sandbox Code Playgroud)
而且,我想要一些效果:
>>> dictionary = {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已尝试过以下内容:
>>> keys = list1
>>> values = list2
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'fruit': 'banana', 'vegetable': 'carrot'}
Run Code Online (Sandbox Code Playgroud)
你可以使用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']}
Run Code Online (Sandbox Code Playgroud)
来自文档:
setdefault(key[, default])
如果
key
在字典中,则返回其值.如果不是,请插入key
值为default
并返回default
.default
默认为None
.
您可以使用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']})
Run Code Online (Sandbox Code Playgroud)
这与其他答案略有不同.这对初学者来说有点简单.
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])
Run Code Online (Sandbox Code Playgroud)
它会回来
{'vegetable': ['carrot'], 'fruit': ['apple', 'banana']}
Run Code Online (Sandbox Code Playgroud)
此代码贯穿list1
并使其中的每个项目成为空列表的键dictionary
.然后它从0-2开始并将每个项目附加list2
到其适当的类别,以便每个匹配的索引0匹配,每个匹配中的索引1和每个匹配的索引2匹配.
归档时间: |
|
查看次数: |
2473 次 |
最近记录: |