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

Keep items with same keys in two dictionary and discard other items

I am trying to remove all non-matching items (values with different keys) in two dicts dict_a and dict_b. What is a better way of achieving this?

Example:

d1 = {key1: x1, key2: y1, key4: z1}
d2 = {key1: x2, key3: y2, key4: w1}
# becomes:
# d1 = {key1: x1, key4: z1}
# d2 = {key1: x2, key4: w1}

My attempt:

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

keep_keys = [keyA for keyA in dict_a.keys() if keyA in dict_b.keys()]

for i in dict_b.copy().keys():
    if i not in keep_keys:
        del dict_b[i]

for i in dict_a.copy().keys():
    if i not in keep_keys:
        del dict_a[i]

I am looking for shorter (pythonic) way of doing this.

>Solution :

You can do:

d1 = {"key1": "x1", "key2": "y1", "key4": "z1"}
d2 = {"key1": "x2", "key3": "y2", "key4": "w1"}

common_keys = d1.keys() & d2.keys()

d1 = {k: d1[k] for k in common_keys}
d2 = {k: d2[k] for k in common_keys}

print(d1)
print(d2)

Prints:

{'key1': 'x1', 'key4': 'z1'}
{'key1': 'x2', 'key4': 'w1'}
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