
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Python Dictionary with Duplicate Keys
In Python, a dictionary doesn't allow duplicate keys or repeated keys. So, we can use defaultdict from the Collections module. As it can store multiple values for the same key in the form of lists or any other data structures.
'defaultdict' from 'collections' Module
The subclass of the built-in dict class that allows us to provide a default value for a key that doesn't exist is known as defaultdict.
A function that returns the default value for new keys is known as 'default factory', and if you want to pass this default factory, we can use a list which allows storing multiple values under the same key.
Handling duplicate keys
The steps involved in creating a dictionary with duplicate keys are as follows.
-
Create a defaultdict with list as the default factory.
-
Consider a list of tuples with duplicate keys and convert them into the defaultdict.
-
Convert the defaultdict into a regular dictionary
'defaultdict' with list as the default factory
We start by importing defaultdict and creating an instance of defaultdict(list) it initializes an empty list for each key when it's first encountered.
from collections import defaultdict d = defaultdict(list)
Initialize list and Converting into defaultdict
considering a list 'l' of tuples containing duplicate keys. Use the key to append the values and loop over this list of tuples.
l = [(1, 111), (2, 222), (3, 333), (1, 'aaa'), (2, 'bbb'), (3, 'ccc')] for k, v in l: d[k].append(v)
Convert the defaultdict to a regular dictionary
Using the dist() method, the defaultdict is converted into an ordinary dictionary.
dict_d = dict(d) print(dict_d)
Final Example
By Utilizing this method, you can arrange many values in a dictionary-like structure under the same key.
from collections import defaultdict # Create defaultdict d = defaultdict(list) # Step 2: List of tuples with duplicate keys l = [(1, 111), (2, 222), (3, 333), (1, 'aaa'), (2, 'bbb'), (3, 'ccc')] # Add values to the defaultdict for k, v in l: d[k].append(v) # Convert defaultdict to a regular dictionary result = dict(d) print(result)
Output
{1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}