Home > database >  How to merge two dictionaries task and only keep matching keys
How to merge two dictionaries task and only keep matching keys

Time:11-19

Write a program in which, based on two dictionaries a new dictionary is created. Into this new the dictionary will include those elements that are represented in each of the source dictionaries (meaning the keys of the elements). The values of the elements in the dictionary being created are sets of the values of the corresponding elements in the source dictionaries

example:

dictionary_1 = {1: 1, 2: 2, 3: 3}
dictionary_2 = {1: 10, 2: 20, 30: 30}
final_dictionaries = {1: {1, 10}, 2: {2, 20}}

my code:

dict1 = {}
dict2 = {}
for i in range(int(input())):
    dict1[input("> ")] = input()
print(dict1)
for i in range(int(input())):
    dict2[input("> ")] = input()
print(dict2)

yes, it is not finished yet, I don’t know what to do next

CodePudding user response:

A dict comprehension using the intersection of their keys will do:

d1 = {1: 1, 2: 2, 3: 3}
d2 = {1: 10, 2: 20, 30: 30}
    
final_d = {k: {d1[k], d2[k]} for k in d1.keys() & d2.keys()}
# {1: {1, 10}, 2: {2, 20}}

CodePudding user response:

Use dict comprehensions, loop over keys in the first dict, only include it if the key is also in the second, and use a set of both values as the value in the new dict.

d1 = {1: 1, 2: 2, 3: 3}
d2 = {1: 10, 2: 20, 30: 30}
d3 = {k: {d1[k], d2[k]} for k in d1 if k in d2}
  • Related