给定两个长度相同的列表:
List1 = ['a','b','c','d','b','a','b','c']
List2 = ['1','2','3','4','5','6','7','8']
我想将 a dict 输出为:
dic = {'a':['1','6'], 'b':['2','5','7'], 'c':['3','8'], 'd':['4']}
如何用Python实现?谢谢!
最佳答案
您可以使用 zip
函数创建一个列列表(在 python 3.X 中是一个迭代器)并使用 dict.setdefault
方法(或 collections.defaultdict
)创建一个愿望字典:
>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>>
>>> d={}
>>> for i,j in zip(List1,List2):
... d.setdefault(i,[]).append(j)
...
>>> d
{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}
如果您关心顺序,您可以使用 collections.OrderedDict
:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in zip(List1,List2):
... d.setdefault(i,[]).append(j)
...
>>> d
OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])
>>>
关于python - 形成一个字典,键来自列表,值是 Python 中另一个列表中项目的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925474/