How do I join dictionaries together in Python?


Python tip:

You can join two dictionaries using ** or | (for Python >= 3.9, works for all subclasses).

If there are any duplicate keys, the second (rightmost) key-value pair is used.

user = {"name": "Jan", "surname": "Giacomelli"}
address = {"address1": "Best street 42", "city": "Best city"}


user_with_city = {**user, **address}
print(user_with_city)
# {'name': 'Jan', 'surname': 'Giacomelli', 'address1': 'Best street 42', 'city': 'Best city'}


user_with_city = user | address
print(user_with_city)
# {'name': 'Jan', 'surname': 'Giacomelli', 'address1': 'Best street 42', 'city': 'Best city'}


user_with_city = {"address": "Best street"} | {"address": "Almost best street"}
print(user_with_city)
# {'address': 'Almost best street'}