In Python, dictionary variables cannot have duplicate keys as by definition, they cannot have duplicate keys.

If you try to define a dictionary with duplicate keys, the last key will be kept with all other duplicate keys removed.

d = {"name":"Bobby", "name":"Sam", "name":"Alex", "height":65, "height":100, "income":65}

print(d)

#Output:
{'name': 'Alex', 'height': 100, 'income': 65}

In Python, dictionaries are a collection of key/value pairs separated by commas.

When working with dictionaries, knowing the definitions and properties can be useful when you are trying to troubleshoot or design a process.

One such dictionary property is that dictionary items are ordered, changeable and do not allow duplicates.

Therefore, you cannot have duplicate keys.

If you try to define a dictionary with duplicate keys, the last key will be kept with all other duplicate keys removed.

d = {"name":"Bobby", "name":"Sam", "name":"Alex", "height":65, "height":100, "income":65}

print(d)

#Output:
{'name': 'Alex', 'height': 100, 'income': 65}

Remove Duplicate Values from Dictionary by Inverting Dictionary in Python

One case where you might have an issue with duplicate keys is if you try to invert a dictionary with duplicate values in Python.

Since dictionaries can only have a unique set of keys, when you go to invert it, you will remove any duplicate values.

Below is an example of inverting a dictionary with duplicate values. You can see that only one key is kept for each value.

d = {"name":"Bobby", "age":20, "credits":20, "height":65, "weight":65, "income":65}

d_inverted = {value: key for key, value in d.items()}

#Output:
{'Bobby': 'name', 20: 'credits', 65: 'income'}

Hopefully this article has been useful for you to learn why dictionary variables in Python cannot have duplicate keys.

Categorized in:

Python,

Last Update: March 12, 2024