Reputation: 161
data = {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5'}
keys = ('one', 'four')
unwanted = set(keys) - set(data)
for unwanted_key in unwanted: del data[unwanted_key]
The output that I want is:
data = {'two': '2', 'three': '3', 'five': '5'}
What am I doing wrong?
I am using the code of this accepted answer.
Upvotes: 0
Views: 146
Reputation: 86
The operation set(keys) - set(data)
will return an empty set as it returns the difference of two sets
but what you need is the intersection of those two sets set(keys) & set(data)
Here's what will work for you:
>>> data = dict(one=1, two=2, three=3, four=4, five=5)
>>> keys = ('one', 'four')
>>> set(data)
{'four', 'one', 'five', 'three', 'two'}
>>> set(keys)
{'four', 'one'}
>>> ukeys = set(data) & set(keys)
>>> ukeys
{'four', 'one'}
>>> for uk in ukeys: del data[uk]
...
>>>
>>> data
{'five': 5, 'three': 3, 'two': 2}
Upvotes: 1
Reputation: 22882
I'm not sure why you need this line:
unwanted = set(keys) - set(data)
Instead, just define your unwanted
keys directly:
>>> data = {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5'}
>>> unwanted = ('one', 'four')
>>> for key in unwanted:
... del data[key]
...
>>> data
{'three': '3', 'five': '5', 'two': '2'}
Upvotes: 5