Python Tip #6 – Merging Dictionaries

Merge or combine dictionaries

d1 = { "a": 1 }
d2 = { "b": 2 }

# Adding elements of one dictionary to another
d1.update(d2)  # d1 => { "a": 1, "b": 2 }

# Create a new dict with values from other dictionaries
d3 = { **d1, **d2 }  # d3 => { "a": 1, "b": 2 }
d4 = { **d3, "c": 3 }  # d4 => { "a": 1, "b": 2, "c": 3 }

** is the unpacking operator

Author: Arunmozhi

Arunmozhi is a freelance programmer and an open-source enthusiast.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.