3

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.

e7lT2P
  • 1,635
  • 5
  • 31
  • 57

4 Answers4

8

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]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
3

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

Netwave
  • 40,134
  • 6
  • 50
  • 93
2

As dict must use unique keys only, and if you insert same key twice the last one will be stored - this might be something you can use:

from itertools import groupby

alist = ['key1','key2','key3','key3','key4','key4','key5']
alist = [i for i, j in groupby(alist)]

blist = [30001,30002,30003,30003,30004,30004,30005]
blist = [list(j) for i, j in groupby(blist)]

print dict(zip(alist, blist))
#{'key3': [30003, 30003], 'key2': [30002], 'key1': [30001], 'key5': [30005], 'key4': [30004, 30004]}

If you want to preserve the key order as well you can use OrderedDict:

from collections import OrderedDict
print OrderedDict(zip(alist, blist))
zipa
  • 27,316
  • 6
  • 40
  • 58
  • This solution does not group `blist` using the key in `alist`, it just groups `blist` by common values, which I don't think is what we're after. For example if we have `['a', 'a', 'b']` and `[1, 2, 3]` we want `{'a': [1, 2], 'b': [3]}`. This solution does not achieve this. – ru111 Sep 26 '22 at 17:13
0

Great answer by @MoinuddinQuadri. I expanded it further to get the index as well:

my_dict = defaultdict(list)
for idx, tup in enumerate(zip(alist, blist)):
    my_dict[tup[0]].append((idx, tup[1])
UNagaswamy
  • 2,068
  • 3
  • 30
  • 35