Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
e7lT2P Avatar asked Dec 07 '25 08:12

e7lT2P


2 Answers

You can not do this as dict objects can only have unique keys. Instead, you should use the 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]
like image 161
Moinuddin Quadri Avatar answered Dec 08 '25 22:12

Moinuddin Quadri


A dictionary uses UNIQUE keys, so its imposible to have duplicates.

like image 36
Netwave Avatar answered Dec 08 '25 20:12

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!