Python Program to Merge Two Dictionaries
Beginner · Dictionaries
Merging two dictionaries means combining their keys and values into one dictionary. When both dictionaries have the same key, only one value can stay, and in Python it is the value from the dictionary added last.
Program
Old prices: {'pen': 10, 'pencil': 5, 'notebook': 40}
New prices: {'pencil': 6, 'eraser': 4}
Merged: {'pen': 10, 'pencil': 6, 'notebook': 40, 'eraser': 4}How it works
copy()makes a separate dictionary, so the originalold_pricesis not changed by the merge.update()adds every key fromnew_prices: "eraser" is new, so it is added, and "pencil" already exists, so its value becomes 6.- A key keeps its first position in the dictionary, so "pencil" stays second even though its value changed.
- Without
copy(),old_prices.update(new_prices)would changeold_pricesitself, which is fine when that is what you want.
Other ways to write it
Using the | operator and unpacking
With |: {'pen': 10, 'pencil': 6, 'notebook': 40, 'eraser': 4}
With **: {'pen': 10, 'pencil': 6, 'notebook': 40, 'eraser': 4}Both make a brand new dictionary and leave the originals alone. As with update(), the dictionary on the right wins when a key is in both.
Adding the values of shared keys
Total stock: {'apples': 30, 'bananas': 32, 'mangoes': 15}Sometimes neither value should win: here the stock of both shops is added together, and get(fruit, 0) gives 0 for a fruit that only the second shop has.
Try it yourself
Swap the order to new_prices | old_prices and see which pencil price wins.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Create a Dictionary from Two Lists
- Merge Two Lists
- Sort a Dictionary by Key
- Find Students Who Scored Above 75 Using a Dictionary
- Sort a Dictionary by Value
- Check if a Key Exists in a Dictionary
- Remove a Key from a Dictionary
- Find the Sum of All Values in a Dictionary
- Find the Key with the Maximum Value in a Dictionary
All Python programs · CBSE class 12 practical file · Python exercises