How to Combine Two Dictionaries in Python
Combining two dictionaries in Python involves merging the key-value pairs from both dictionaries while handling common keys appropriately. Let's take a look at how we can achieve this:
Steps to Combine Two Dictionaries and Collect Values of Common Keys in a List:
- Iterate over the keys in the first dictionary (dict1).
- If the key exists in the second dictionary (dict2), add the key along with the values of both dictionaries to a new dictionary. Append values of common keys to a list.
- If the key only exists in one dictionary, add the key-value pair to the new dictionary.
- Repeat the same process for the keys in the second dictionary (dict2) that are not already in the new dictionary.
- Return the new dictionary with combined key-value pairs.
Here's an example Python function to demonstrate combining two dictionaries and collecting values of common keys in a list:
def combine_dictionaries(dict1, dict2):
combined_dict = {}
for key in dict1:
if key in dict2:
combined_dict[key] = [dict1[key], dict2[key]]
else:
combined_dict[key] = dict1[key]
for key in dict2:
if key not in combined_dict:
combined_dict[key] = dict2[key]
return combined_dict
In the example function above, if dict1 = {'a': 1, 'b': 2} and dict2 = {'a': 3, 'c': 4}, the resulting combined_dict would be {'a': [1, 3], 'b': 2, 'c': 4}.