Aaron Mazie
Aaron Mazie

Reputation: 763

Deleting Dictionaries Keys with a For If Statement in Python 3

I feel very dumb asking this. How do I delete a keys in a dictionary with an if statement that references the values. When I do this:

newdict = {"a":1,"b":2,"c":3}

for (key,value) in newdict:
    if value == 2:
        del newdict[key]
print(newdict)

It throws this error:

line 3, in <module>
    for (key,value) in newdict:
ValueError: not enough values to unpack (expected 2, got 1)

Thank you.

Upvotes: 1

Views: 254

Answers (1)

Innat
Innat

Reputation: 17219

If you need to delete based on the items value, use the items() method or it'll give ValueError. But remember if you do so it'll give a RuntimeError. This happens because newdict.items() returns an iterator not a list. So, Convert newdict.items() to a list and it should work. Change a bit of above code like following -

for key,value in list(newdict.items()):
    if value == 2:
        del newdict[key]

output -

{'a': 1, 'c': 3}

Upvotes: 1

Related Questions