dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} merged_dict = {**dict1, **dict2} print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
To merge two dictionaries in a single expression in Python, you can use the {**dict1, **dict2} syntax, which is also known as double-starred dictionary unpacking. This syntax allows you to combine the key-value pairs from two dictionaries into a new dictionary.
In this example, the dictionaries dict1 and dict2 are merged into a new dictionary called merged_dict. This dictionary contains the key-value pairs from both of the original dictionaries.
Note that if the same key appears in both dictionaries, the value from the second dictionary (dict2 in this case) will overwrite the value from the first dictionary (dict1). For example:
dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged_dict = {**dict1, **dict2} print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
In this example, the b key appears in both dictionaries, with a value of 2 in dict1 and a value of 3 in dict2. When the dictionaries are merged, the value of 3 overwrites the value of 2, and the resulting merged_dict dictionary contains the key-value pair 'b': 3.
The double-starred dictionary unpacking syntax is a concise and efficient way to merge two dictionaries in Python. It can be useful in situations where you need to combine the data from multiple dictionaries into a single dictionary, such as when working with data from multiple sources or in different formats.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.