user2983258
user2983258

Reputation: 161

Remove values from dictionary based on key values

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.

DEMO

Upvotes: 0

Views: 146

Answers (2)

ustinov
ustinov

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

mdml
mdml

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

Related Questions