This tutorial will discuss how to adding duplicate key to a Python dictionary.
We cannot add a duplicate key into a Python dictionary. The reason is that dictionary keys must be unique; there can be no duplicate keys.
So, suppose we create an empty dictionary and add a key-value pair into it. Now, if we try to add a new key-value pair but with the same key, it will update the value of the existing key instead of adding a new key-value pair. Thus, we cannot add duplicate keys into a Python dictionary.
Let’s see the complete example,
# Create an empty dictionary my_dict = {} # Add key-value pairs with the same key my_dict["key1"] = "value1" my_dict["key1"] = "value2" # Print the updated dictionary print(my_dict)
Output
{'key1': 'value2'}
However, if you are trying to add a duplicate key into a Python dictionary, it suggests that you have a particular requirement but are trying to handle it differently. It’s possible you want to assign multiple values to a single key, which you can do by assigning a list or another container type to the key.
Let’s see the complete example,
Frequently Asked:
# Create a dictionary with a list as the value my_dict = { "key1": [1, 2, 3], "key2": [4, 5, 6]} # Print the dictionary print(my_dict)
Output
{'key1': [1, 2, 3], 'key2': [4, 5, 6]}
Summary
Today, we learned how to adding duplicate key to a Python dictionary.