Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading