3

I can club two lists into a dictionary as below -

list1 = [1,2,3,4]
list2 = ['a','b','c','d']
dct = dict(zip(list1, list2))
print(dct)

Result,

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

However with duplicates as below,

list3 = [1,2,3,3,4,4]
list4 = ['a','b','c','d','e','f']
dct_ = dict(zip(list1, list2))
print(dct)

I get,

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

What should i do to consider the duplicates in my list as individual keys in my resulting dictionary?

I am expecting results as below -

{1: 'a', 2: 'b', 3: 'c', 3: 'd', 4: 'e', 4: 'f'}
  • 4
    This is not possible with a `dict`. A key can appear at most once. – Michael Butscher Dec 09 '18 at 01:37
  • @Michael Butscher is there any other way i can implement this(mapping between the lists irrespective of the duplicates in the lists)? I need to use this in my application. –  Dec 09 '18 at 01:42
  • @Rohit see YOLO's answer. – Ned Batchelder Dec 09 '18 at 01:44
  • 1
    Possible duplicate of [list to dictionary conversion with multiple values per key?](https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key) – wwii Dec 09 '18 at 02:00

2 Answers2

5

Instead you can create the dictionary with values as list:

from collections import defaultdict
d = defaultdict(list)

for k,v in zip(list3, list4):
    d[k].append(v)

defaultdict(list, {1: ['a'], 2: ['b'], 3: ['c', 'd'], 4: ['e', 'f']})
YOLO
  • 20,181
  • 5
  • 20
  • 40
  • 1
    `d[k].append(v)` would be better. As is, you replace the list with a fresh one each time, that's too much copying. –  Dec 09 '18 at 02:12
0

You can't have duplicate keys in a dictionary. However, you can have multiple values(a list) mapped to each key.

An easy way to do this is with dict.setdefault():

list3 = [1,2,3,3,4,4]
list4 = ['a','b','c','d','e','f']

d = {}
for x, y in zip(list3, list4):
    d.setdefault(x, []).append(y)

print(d)
# {1: ['a'], 2: ['b'], 3: ['c', 'd'], 4: ['e', 'f']}

The other option is to use a collections.defaultdict(), as shown in @YOLO's answer.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75