1

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.

Aaron Mazie
  • 743
  • 6
  • 13

1 Answers1

1

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}
M.Innat
  • 13,008
  • 6
  • 38
  • 74