10.1k views
1 vote
It takes two dictionaries as parameters, dict 1 and dict 2 and returns a new dictionary that combines dict1 and dict2, collecting the values of common keys in a list.

1 Answer

4 votes

Final answer:

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

Step-by-step explanation:

This question relates to the field of Computers and Technology. The task is to combine two dictionaries, dict1 and dict2, and create a new dictionary that collects the values of common keys in a list. To accomplish this, we can iterate over the keys in dict1 and dict2. If a key exists in both dictionaries, we can add the corresponding values to a list in the new dictionary. If a key only exists in one of the dictionaries, we simply add the key-value pair to the new dictionary. Here's an example:

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 this example, 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}.

User PRASHANT P
by
8.8k points