Can a dictionary have duplicate keys in Python?

In this article, we will find out whether a dictionary has duplicate keys or not in Python.

The straight answer is NO. You can not have duplicate keys in a dictionary in Python. But we can have a similar effect as keeping duplicate keys in dictionary. We need to understand the reason behind this question and how we can achieve duplicate keys in Python.

Why you can not have duplicate keys in a dictionary?

You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.

Let’s understand with an example,

Suppose we have a dictionary of names and phone numbers,

# Dictionary of names and phone numbers
phone_details = {   'Mathew': 212323,
                    'Ritika': 334455,
                    'John'  : 345323 }

As of now, each name (key) has a phone number associated with it. But suppose “John” has two more phone numbers, and we want to add those too in the dictionary. As the Key ‘John’ already exist in the dictionary, so if we try adding two more key-value pair with the same key like this,

phone_details['John'] = 111223
phone_details['John'] = 333444

OR

phone_details.update({ 'John' : 111223})
phone_details.update({ 'John' : 333444})

It will update the value of the existing key ‘John’ i.e.

Mathew  -  212323
Ritika  -  334455
John  -  333444 

To avoid this kind of problem, we can assign multiple values to a single key. Like this,

Mathew  -  212323
Ritika  -  334455
John  -  [345323, 111223, 333444]

Adding multiple values for a key in dictionary in Python

Instead of inserting a duplicate key, we can change the type of value to the list and assign more values to it.

Let’s see an example,

def add_value(dict_obj, key, value):
    ''' Adds a key-value pair to the dictionary.
        If the key already exists in the dictionary, 
        it will associate multiple values with that 
        key instead of overwritting its value'''
    if key not in dict_obj:
        dict_obj[key] = value
    elif isinstance(dict_obj[key], list):
        dict_obj[key].append(value)
    else:
        dict_obj[key] = [dict_obj[key], value]


# Dictionary of names and phone numbers
phone_details = {   'Mathew': 212323,
                    'Ritika': 334455,
                    'John'  : 345323 }

# Append a value to the existing key 
add_value(phone_details, 'John', 111223)
# Append a value to the existing key
add_value(phone_details, 'John', 333444)

for key, value in phone_details.items():
    print(key, ' - ', value)

Output

Mathew  -  212323
Ritika  -  334455
John  -  [345323, 111223, 333444]

Here we created a function add_value() that adds a key-value pair to the dictionary. If the key already exists in the dictionary, it will associate multiple values with that key instead of overwritting its value. It follows this logic.

  • If the key does not exist, then add the key-value pair.
  • If key exists in dictionary and type of value is not list. Then create a temporary list and add old and new values to it. Then assign the list object as the value for the key in dictionary.
  • If key exists in dictionary and type of value is a list. Then add new value to the list.

So, this is how we can have duplicate keys in a dictionary, i.e., by adding multiple values for the same key in a dictionary in Python.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top