'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'.
Solution 1:[1]
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}
Solution 2:[2]
EDIT: I've realized I didn't actually answer the specific question, but I'll leave this up since some people seem to have found it useful for the general task of removing items from dictionaries. For a solution to the question asked, see this answer from solid.py or this answer from Richard K Yu.
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])
Solution 3:[3]
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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Richard K Yu |