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