In this Python Tutorial, we will see how to update duplicate keys in Python Dictionary using some examples. We will learn various methods to update duplicate keys in Python Dictionary.
Duplicate keys are not allowed in Python dictionary, what will happen if we try to give two keys, the same name but different values?
For example, we can see below there is a Python dictionary that has two duplicate keys in it.
Dict = {
'Sam': 'Block A',
'Ian': 'Block C',
'Eva': 'Block B',
'Amy': 'Block D',
'Sam': 'Block B'
}
You know, what will happen if we print out the dictionary in Python:
Dictionary with duplicate keys:
{'Sam': 'Block B', 'Ian': 'Block C', 'Eva': 'Block B', 'Amy': 'Block D'}
The Duplicate key will automatically get updated with the last insert value in a dictionary. Or, we can say, the keys hold only one value in a dictionary i.e., the last inserted value.
We can update these duplicate keys from a dictionary in Python by using the below 4 methods:
- Navie Approach
- Update() Method
- Using For loop
- Using **(double asterisks)
Update duplicate keys in Python Dictionary
As we all know, keys in Python dictionaries are always unique.
What will happen when we will try to insert a duplicate key every time using the different methods listed above?
Method-1: The naive approach in Python
In this process of updating duplicate keys in a Python dictionary, we use the general way to update any key: value pair in Python.
Firstly, we will create an initial Python dictionary. And, then we will add two pairs of keys: values in the initial dictionary. We will see what happens next.
In the below code of Python, Day one, of a company we are creating a dictionary with the names of employees as keys and their degree names as values. On day two, two new employees came and we try to add them to the existing Python dictionary. But, one of the employee names is the same as one of the previously entered names.
# initial dictionary
Employees = {
'Mia': 'CS',
'Leo': 'Pharma',
'Ian': 'CS',
'Kai': 'Finance',
'Max': 'Pharma',
'Gia': 'HR',
'Mike': 'CS'
}
# printing initial dictionary
print('Employees log with their degrees are:\n', Employees)
# entering two new values in initial dictionary
Employees['Mia'] = 'Health'
Employees['Rob'] = 'Admin'
# printing the changed dictionary
print('The updated Employees log with their degrees are:\n', Employees)
The output of this :
Employees log with their degrees are:
{'Mia': 'CS', 'Leo': 'Pharma', 'Ian': 'CS', 'Kai': 'Finance', 'Max': 'Pharma', 'Gia': 'HR', 'Mike': 'CS'}
The updated Employees log with their degrees are:
{'Mia': 'Health', 'Leo': 'Pharma', 'Ian': 'CS', 'Kai': 'Finance', 'Max': 'Pharma', 'Gia': 'HR', 'Mike': 'CS', 'Rob': 'Admin'}
As we can see, there are two employees named Mia, and the first entered value is getting replaced by the second one. But the second employee(Rob) from day two who doesn’t have any duplicate value gets easily updated to the Python dictionary.
Method-2: Using Python update() method
By using the update() method, we will see that there are three ways to update keys in the Python dictionary. they are as follows:
- Updating with Iterables
- Update with one key-value pair
- Update with another dictionary
Updating Dictionary Key with iterable in Python
Here, we will create the initial Python dictionary. And, then we will use the Python update() method to update an iterable in the dictionary.
In this example, we have factory inventory details as a dictionary with items as keys and amounts as values. The next day we update the inventory.
# initial dicitionary
inventory = {
'Badge': 25,
'Laptop': 15,
'keys': 45,
'cell phones': 18
}
print('Inventory present: \n', inventory)
inventory.update(Badge=45, Book=12)
print('Inventory updated:\n', inventory)
The output of this:
Inventory present:
{'Badge': 25, 'Laptop': 15, 'keys': 45, 'cell phones': 18}
Inventory updated:
{'Badge': 45, 'Laptop': 15, 'keys': 45, 'cell phones': 18, 'Book': 12}
We get the updated dictionary as the Badge value gets updated while the book gets added to the inventory dictionary.
Read How to copy specific keys in Python Dictionary
Update the Python Dictionary key with one key-value pair
Here, we will create the initial Python dictionary. And, then we will use the Python update() method to update the dictionary with one key-value pair.
In the below example, we are creating a log for the top cars sold in the USA in 2022. With names of cars as keys and the number of cars sold in values. After one month, we are updating the log.
# using update method
cars2022 = {
'Toyota Camry': '1.5k',
'Honda Civic': '1.2k',
'Toyota Corolla': '1.03k',
'Toyota RAV4': '0.40k',
'Chevrolet Silverado': '0.35k'
}
print('top cars sold in USA in 2022 are: \n', cars2022)
cars2022.update({'Chevrolet Silverado': '0.20k'})
print('the updated cars sold in USA in 2022 are: \n', cars2022)
The output of this code:
top cars sold in USA in 2022 are:
{'Toyota Camry': '1.5k', 'Honda Civic': '1.2k', 'Toyota Corolla': '1.03k', 'Toyota RAV4': '0.40k', 'Chevrolet Silverado': '0.35k'}
the updated cars sold in USA in 2022 are:
{'Toyota Camry': '1.5k', 'Honda Civic': '1.2k', 'Toyota Corolla': '1.03k', 'Toyota RAV4': '0.40k', 'Chevrolet Silverado': '20.5k'}
This is another way we can update the Python dictionary using the update() method.
Update with another Python dictionary
Here, we will create the initial dictionary and a temporary Python dictionary. And, then we will use the Python update() method to update the initial dictionary with the temporary dictionary.
In the below example, A girl is carrying three bags before she goes to the shop. when she came back she has four bags in her hand. so, we will check what has happened with the bags in the shop.
# dict 1
bags = {
'Bag_A': 'Doritos',
'Bag_B': 'Galaxy',
'Bag_C': 'Oreo'
}
print('Bags before going to the shop:\n', bags)
# dict 2
shop = {
'Bag_C': 'Diet coke',
'Bag_D': 'Debbie'
}
# using update method
bags.update(shop)
# printing result
print('Bags after coming back from the shop:\n ', bags)
The output of the code:
Bags before going to the shop:
{'Bag_A': 'Doritos', 'Bag_B': 'Galaxy', 'Bag_C': 'Oreo'}
Bags after coming back from the shop:
{'Bag_A': 'Doritos', 'Bag_B': 'Galaxy', 'Bag_C': 'Diet coke', 'Bag_D': 'Debbie'}
As we can see, the keys get updated with the values. This way we can use the update() method to update duplicate keys.
Method-3: Using Python For loop
In this method, we will use the Python for loop to update the duplicate key in the Python dictionary. Here, we will have two different dictionaries with some common keys in them.
We will create an empty Python dictionary and assign that to a variable. Then we will loop through both dictionaries, And, every time we loop over them, the key and value of the respective Python dictionary items will get stored in the empty dictionary.
In the example, we have cars with their ranking in the form of Python dictionaries. the first one was created in the first six months of the year and another one was created in the last six months.
We have to submit a report for the whole year. So, we have to merge both reports and make a report showing the result.
# using for loop
cars_first_six_months = {
'1st': 'Ford F-Series',
'2nd': 'Chevrolet Silverado',
'3rd': 'Ram Pick-Up',
}
cars_last_six_months = {
'3rd': 'Toyota RAV4',
'4th': 'Ram Pick-up'
}
cars_2023 = dict()
# using for loop
for dic in (cars_first_six_months, cars_last_six_months):
for key, value in dic.items():
cars_2023[key] = value
print('top cars sold in USA 2023 are: \n', cars_2023)
The output of the above-written code is:
top cars sold in USA 2023 are:
{'1st': 'Ford F-Series', '2nd': 'Chevrolet Silverado', '3rd': 'Toyota RAV4', '4th': 'Ram Pick-up'}
This way we change the key in the Python dictionary using For loop.
Method-4: Using **(double asterisks) in Python
In this process, we will simply merge two Python dictionaries using double asterisks. Here, we have two different dictionaries with some common key names. We will integrate them into a single expression.
In this example, we have a Python dictionary with chapter names in the order we want to put. But, another day we decided to change the titles and put them in another Python dictionary. Finally, we have to give the dictionary with the correct names of the titles in it.
chapter_day1 = {'1st': 'lost battle', '2nd': 'broken', '3rd': 'fighting_back'}
chapter_day2 = {'2nd': 'false hope', '3rd': 'unbroken', '4th': 'fighting_back'}
Book = dict(chapter_day1, **chapter_day2)
print('Book chapters are gonna be :\n', Book)
The output of the code :
Book chapters are gonna be :
{'1st': 'lost battle', '2nd': 'false hope', '3rd': 'unbroken', '4th': 'fighting_back'}
This way we can update the duplicate keys in a dictionary in Python.
Conclusion
In this tutorial, we have seen four different ways how to update duplicate keys in a Dictionary in Python. It is easy to update the values for the key in the dictionary, but impossible to add two duplicate keys.
You may like to read:
- How to remove duplicate values from a Python Dictionary
- How to convert a nested dictionary to json in Python
- Python Dictionary Methods
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.