How to create Python dictionary with duplicate keys?


Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround. This class is defined in collections module.

Use list as default factory for defaultdict object

>>> from collections import defaultdict
>>> d=defaultdict(list)

Here is a list of tuples each with two items. First item is found to be repeatedly used. This list is converted in defaultdict

>>> for k,v in l:
      d[k].append(v)

Convert this defaultdict in a dictionary object using dict() function

>>> dict(d)
{1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}


Updated on: 04-Dec-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements