How do I merge two dictionaries in a single expression?
You can use the update()
method of one dictionary to merge the key-value pairs from another dictionary into it. For example:
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d1.update(d2)
print(d1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Watch a video course
Python - The Practical Guide
Alternatively, you can use the {**d1, **d2}
syntax to create a new dictionary that contains the key-value pairs from both d1
and d2
. This syntax is available in Python 3.5 and newer.
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {**d1, **d2}
print(d3) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
This syntax is known as the double-starred dictionary (or "unpacking") syntax. It allows you to expand the key-value pairs in one dictionary into another dictionary.