user5389245
user5389245

Reputation:

Convert a pair of list objects into dictionary with duplicates included

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'}

Upvotes: 3

Views: 903

Answers (2)

YOLO
YOLO

Reputation: 21709

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

Upvotes: 5

RoadRunner
RoadRunner

Reputation: 26315

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.

Upvotes: 0

Related Questions