Python: Merge two dictionaries into one dictionary

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)
python merge two dict into one in one line of code

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!