创建每个键多个值的字典 [英] Create dictionary with multiple values per key
本文介绍了创建每个键多个值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有:
>>> list1 = ['fruit','fruit','vegetable']
>>> list2 = ['apple','banana','carrot']
而且,我想要一些东西的效果:
>>>字典= {'fruit':['apple','banana'],'vegetable':['carrot']}
我已经尝试过以下目录:
>>> keys = list1
>>> values = list2
>>> dictionary = dict(zip(keys,values))
>>>字典
{'fruit':'banana','vegetable':'carrot'}
解决方案
您可以使用 这些任务的collections.defaultdict :
>>> from collections import defaultdict
>>>> d = defaultdict(list)
>>>对于i,j在zip(list1,list2)中:
... d [i] .append(j)
...
>>> d
defaultdict(< type'list'>,{'vegetable':['carrot'],'fruit':['apple','banana']})
How can I create a dictionary with multiple values per key from 2 lists?
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 collections.defaultdict for such tasks :
>>> 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']})
这篇关于创建每个键多个值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文