369
369

Reputation: 37

How to merge two dictionaries task and only keep matching keys

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

Upvotes: 0

Views: 1086

Answers (2)

Pieter
Pieter

Reputation: 3447

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}

Upvotes: 1

user2390182
user2390182

Reputation: 73480

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}}

Upvotes: 2

Related Questions