压缩字典中的两个列表,但在关键字中保留重复项 [英] Zip two lists in dictionary but keep duplicates in key
问题描述
我有两个列表:
alist = ['key1','key2','key3','key3','key4','key4','key5']
blist= [30001,30002,30003,30003,30004,30004,30005]
我想合并这些列表并将其添加到字典中.
I want to merge these lists and add them to a dictionary.
我尝试dict(zip(alist,blist))
,但这给出了:
{'key3':30003,'key2':30002,'key1':30001,'key5':30005,'key4': 30004}
{'key3': 30003, 'key2': 30002, 'key1': 30001, 'key5': 30005, 'key4': 30004}
所需的字典形式是:
{'key1':30001,'key2':30002,'key3':30003,'key3':30003,'key4':30004,'key4': 30004,"key5":30005}
{'key1': 30001, 'key2': 30002, 'key3': 30003,'key3':30003, 'key4': 30004, 'key4': 30004, 'key5': 30005}
我想将重复项保留在字典中,并且不希望将值加入同一键(... key3':30003,'key3':30003,...).可以吗?
I want to keep the duplicates in the dictionary as well as not join the values in the same key (... key3': 30003,'key3':30003,... ).Is it possible?
谢谢.
推荐答案
您不能这样做,因为dict
对象具有唯一键.您应该只使用元组的列表:
You can not do that as dict
objects have unique keys. You should just the use list of tuple:
>>> alist = ['key1','key2','key3','key3','key4','key4','key5']
>>> blist= [30001,30002,30003,30003,30004,30004,30005]
>>> zip(alist, blist)
[('key1', 30001), ('key2', 30002), ('key3', 30003), ('key3', 30003), ('key4', 30004), ('key4', 30004), ('key5', 30005)]
如果要基于键访问所有值,则可以将collections.defaultdict
用作:
If you want to access all the values based on the key, you may use collections.defaultdict
as:
>>> from collections import defaultdict
>>> my_dict = defaultdict(list)
>>> for k, v in zip(alist, blist):
... my_dict[k].append(v)
...
>>> my_dict
defaultdict(<type 'list'>, {'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]})
您可以访问defaultdict
,类似于普通的dict对象.例如:
You can access defaultdict
similar to normal dict objects. For example:
>>> my_dict['key3']
[30003, 30003]
这篇关于压缩字典中的两个列表,但在关键字中保留重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!