Sunday, March 19, 2023

Given two dictionaries d1 and d2, write a function mergeDic that accepts two dictionaries d1 and d2 and return a new dictionary by merging d1 and d2.



Given two dictionaries d1 and d2, write a function mergeDic that accepts two dictionaries d1 and d2 and return a new dictionary by merging d1 and d2. 
Note: Contents of d1 should be appear before contents of d2 in the new dictionary and in same order. In case of duplicate value retain the value present in d1.

Input:

{1: 1, 2: 2}
{3: 3, 4: 4}

output:
{1: 1, 2: 2, 3: 3, 4: 4}

Python Code:

def mergeDic(d1, d2):
    merged = {}
    for key, value in d1.items():
        merged[key] = value
    for key, value in d2.items():
        if key not in merged:
            merged[key] = value
    return merged
key = list(map(int, input().split()))
val = list(map(int, input().split()))

d1 = {}
for i in range(len(key)):
    d1[key[i]] = val[i]
    
d2 = {}
key = list(map(int, input().split()))
val = list(map(int, input().split()))
for i in range(len(key)):
    d2[key[i]] = val[i]

print(mergeDic(d1, d2))


Explanation :

The function creates an empty dictionary called merged and then iterates through the key-value pairs in d1. For each pair, it adds the key-value pair to the merged dictionary. Then it iterates through the key-value pairs in d2. For each pair, it checks if the key is already in merged. If the key is not in merged, it adds the key-value pair to the merged dictionary. Finally, it returns the merged dictionary.

Note that the function checks if a key is already in merged before adding it from d2. This is to ensure that values from d1 are retained in case of duplicates.


No comments:

Post a Comment