How to create Python dictionary with duplicate keys?

PythonServer Side ProgrammingProgramming

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


raja
Published on 05-Jun-2021 04:04:37
Advertisements