Python Program to combine two dictionaries having key of the first dictionary and value of the secon

Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and value from the second dictionary.

d dictionary

Here's a Python program that combines two dictionaries, taking the keys from the first dictionary and the values from the second dictionary: 

 

def combine_dicts(dict1, dict2):
    """
    Combine two dictionaries into one, using the keys from dict1 and the values from dict2.
    """
    combined_dict = {}
    for key in dict1:
        if key in dict2:
            combined_dict[key] = dict2[key]
    return combined_dict

# Example usage
dict1 = {'apple': 1, 'banana': 2, 'orange': 3}
dict2 = {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}
combined_dict = combine_dicts(dict1, dict2)
print(combined_dict) # Output: {'apple': 'red', 'banana': 'yellow', 'orange': 'orange'}

In this program, the function combine_dicts() takes two dictionaries, dict1 and dict2, as arguments. It creates an empty dictionary combined_dict to store the combined key-value pairs.

The program then iterates through the keys of dict1 using a for loop. For each key, it checks if that key is also present in dict2 using an if statement. If the key is present in both dictionaries, the value from dict2 is added to combined_dict with the corresponding key from dict1.

Finally, the function returns the combined dictionary.

In the example usage, we create two dictionaries dict1 and dict2 with the same keys but different values. We then call combine_dicts() with these dictionaries as arguments, and print the resulting combined dictionary. The output is a new dictionary with the keys from dict1 and the values from dict2.

Submit Your Programming Assignment Details