dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print("Concatenated Dictionary:", dict1)
#source code --> clcoding.com
Code Explanation:
Define Two Dictionaries:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1 and dict2 are dictionaries with key-value pairs.
dict1 has keys 'a' and 'b' with values 1 and 2, respectively.
dict2 has keys 'c' and 'd' with values 3 and 4.
Merge Dictionaries:
dict1.update(dict2)
The update() method updates dict1 by adding key-value pairs from dict2.
If a key in dict2 already exists in dict1, the value from dict2 will overwrite the one in dict1.
After this operation, dict1 will contain all key-value pairs from both dict1 and dict2.
Print the Result:
print("Concatenated Dictionary:", dict1)
This prints the updated dict1, showing that it now includes the contents of dict2 as well.
Output:
Concatenated Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
The output confirms that dict1 now contains all key-value pairs from both dictionaries.
Key Points:
The update() method is an in-place operation, meaning it modifies dict1 directly.
If you need a new dictionary without modifying the originals, you can use the ** unpacking method:
combined_dict = {**dict1, **dict2}
0 Comments:
Post a Comment