Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

python - Zip two lists in dictionary but keep duplicates in key

I have two lists:

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.

I try dict(zip(alist,blist)) but this gives:

{'key3': 30003, 'key2': 30002, 'key1': 30001, 'key5': 30005, 'key4': 30004}

The desired form of the dictionary is:

{'key1': 30001, 'key2': 30002, 'key3': 30003,'key3':30003, 'key4': 30004, 'key4': 30004, 'key5': 30005}

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?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)]

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]})

You can access defaultdict similar to normal dict objects. For example:

>>> my_dict['key3']
[30003, 30003]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...