How to Combine Two Dictionaries in Python

How can we combine two dictionaries in Python and collect the values of common keys in a list? To combine two dictionaries in Python and collect the values of common keys in a list, we can iterate over the keys in both dictionaries and add the corresponding values to a new dictionary. If a key only exists in one dictionary, we simply add the key-value pair to the new dictionary. If a key is common to both dictionaries, we collect the values in a list.

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:

  1. Iterate over the keys in the first dictionary (dict1).
  2. 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.
  3. If the key only exists in one dictionary, add the key-value pair to the new dictionary.
  4. Repeat the same process for the keys in the second dictionary (dict2) that are not already in the new dictionary.
  5. 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}.

← Final answer increasing budget for campaigns with specific queries Using yum command in red hat and fedora linux →