Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to create Python dictionary with duplicate keys?

How to create Python dictionary with duplicate keys?                                             


1 Answer
Jayashree

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.