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.
You can use the update() method of one dictionary to merge the key-value pairs from another dictionary into it. For example:
merge dictionaries by update method in Python
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d1.update(d2)
print(d1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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.
merge dictionaries by ** in Python
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.