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

Delete (a, b) in dictionary_1 if a in dictionary_2

I have two dictionaries

D1 = {('one', 'two'): 3, ('three', 'four'): 5, ('five', 'six'): 7, ('eight', 'nigh'):8} 
D2 = {'one':1, 'five': 2}

I want to delete ('one', 'two'): 3 and ('five', 'six'): 7 in D1, because D2 contains ‘one’ and ‘five’.

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

>Solution :

One way to achieve this would be to construct a new dictionary D3 using a dict comprehension, which does not contain element whose keys are present in D2. This works by excluding elements which have their tuples share elements with the keys of D2. Τhis comparison happens using set intersection & between the set of elements of each key of D1 and the set of keys of D2.

D1 = {('one', 'two'): 3, ('three', 'four'): 5, ('five', 'six'): 7, ('eight', 'nigh'):8} 
D2 = {'one':1, 'five': 2}


D3 = {k: v for k, v in D1.items() if not set(k) & set(D2)}
print(D3)

Output:

{('three', 'four'): 5, ('eight', 'nigh'): 8}
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