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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap