Editor

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

merge_dictionaries.py
old_prices = {"pen": 10, "pencil": 5, "notebook": 40}
new_prices = {"pencil": 6, "eraser": 4}
merged = old_prices.copy() # copy, so old_prices stays unchanged
merged.update(new_prices) # add new keys and overwrite shared ones
print("Old prices:", old_prices)
print("New prices:", new_prices)
print("Merged: ", merged)
Output
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

  1. copy() makes a separate dictionary, so the original old_prices is not changed by the merge.
  2. update() adds every key from new_prices: "eraser" is new, so it is added, and "pencil" already exists, so its value becomes 6.
  3. A key keeps its first position in the dictionary, so "pencil" stays second even though its value changed.
  4. Without copy(), old_prices.update(new_prices) would change old_prices itself, which is fine when that is what you want.

Other ways to write it

Using the | operator and unpacking

Using the | operator and unpacking
old_prices = {"pen": 10, "pencil": 5, "notebook": 40}
new_prices = {"pencil": 6, "eraser": 4}
print("With |: ", old_prices | new_prices) # Python 3.9 and later
print("With **:", {**old_prices, **new_prices}) # works in older versions too
Output
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

Adding the values of shared keys
shop_a = {"apples": 30, "bananas": 12}
shop_b = {"bananas": 20, "mangoes": 15}
total = shop_a.copy()
for fruit, count in shop_b.items():
total[fruit] = total.get(fruit, 0) + count
print("Total stock:", total)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises