Home > Software design >  Delete (a, b) in dictionary_1 if a in dictionary_2
Delete (a, b) in dictionary_1 if a in dictionary_2

Time:01-25

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'.

CodePudding user response:

You can iterate over the keys in a dictionary like so:

for key in my_dict:
    do_something_with_key()

And you can remove an item from a dict by deleting the key. So one solution to your problem is:

for key in D2:
    del(D1[key])

CodePudding user response:

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}

CodePudding user response:

As MichaelCG8 suggests, you need to access the keys in the dictionary through iteration.

The main idea is that you need to check whether one of the keys in D2 exists in the tuple that is the key of D1. Definitely give the problem a go yourself after you understand the idea!

One way you can do this is:

to_remove = []

for key in D2.keys():
    for tup in D1.keys():
        if key in tup:
            to_remove.append(tup)

for remove in to_remove:
    del(D1[remove])

print(D1)

In the code above, we check for all keys that fit your condition, put them into a list, and then delete them from D1.

Output:

{('three', 'four'): 5, ('eight', 'nigh'): 8}

  •  Tags:  
  • Related