There are many ways to merge two Python dictionaries into one dictionary (dict), let's take a look at how to do this in just one line of code.
Example 1: Using dictionary unpacking
new_york_dict_1 = {'city': 'New York', 'population': 8537673, 'timezone': 'EST', 'state': 'New York'}
new_york_dict_2 = {'city': 'New York', 'country': 'United States', 'area': 783.8}
merged_dict = {**new_york_dict_1, **new_york_dict_2}
print(merged_dict)
Output:
{
'city': 'New York',
'population': 8537673,
'timezone': 'EST',
'state': 'New York',
'country': 'United States',
'area': 783.8
}
Example 2: Merge using | Operator (PEP 584)
new_york_dict_1 = {'city': 'New York', 'population': 8537673, 'timezone': 'EST', 'state': 'New York'}
new_york_dict_2 = {'city': 'New York', 'country': 'United States', 'area': 783.8}
merged_dict = merged_dict = new_york_dict_1 | new_york_dict_2
print(merged_dict)

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!