1

I have some code that iterates over the values of a dictionary. If the value meets certain conditions, it is deleted from the dictionary. Those conditions are contingent on the existence of other values in the dictionary. This is why I don't want to just copy the old dictionary and make deletions, then re-attribute it.

When I try to run it, I get an error that the size of the dictionary changed while iterating it. Is there a way to iterate over a dictionary that allows it to change size, and the existence of keys and values, while it is iterating?

jukhamil
  • 779
  • 2
  • 11
  • 18
  • Iterate over a copy (of just the keys), but remove elements and check the conditions on the original? – tobias_k Jul 28 '15 at 20:57
  • It would still iterate over every key in the original dictionary; but by the time it got to some of those keys, those values would have been deleted. So I want it to change its own iteration once a value is deleted. – jukhamil Jul 28 '15 at 21:00
  • possible duplicate of [How to delete items from a dictionary while iterating over it?](http://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it) – Kevin Jul 29 '15 at 02:17

3 Answers3

2

Build a new dictionary which contains the keys you want to keep. This can be done with a dictionary comprehension, or a manual for loop.

Here's a comprehension:

return {k: v for k, v in my_dict.items() if some-condition}

Here's a manual loop:

result = {}
for k, v in my_dict.items():
    if some-condition:
        result[k] = v
return result
Kevin
  • 28,963
  • 9
  • 62
  • 81
1

Well, yes you can iterate on by the keys (Python3)! Take a look:

>>> dc
{1: 'aze', 3: 'poi', 4: 'mlk'}
>>> dc = {1:"aze", 2:"qsd", 3:"poi", 4:"mlk"}
>>> dc
{1: 'aze', 2: 'qsd', 3: 'poi', 4: 'mlk'}
>>> keys = list(dc.keys())
>>> keys
[1, 2, 3, 4]
>>> for k in keys:
    if "q" in dc[k]:
        del dc[k]


>>> dc
{1: 'aze', 3: 'poi', 4: 'mlk'}
>>> 
Clodion
  • 1,017
  • 6
  • 12
0

You can iterate over the keys instead of over the dict itself. In the following example, all values that are odd-numbered are removed from the dict:

>>> a = {'a': 12,  'b': 3, 'c': 14}
>>> for key in list(a.keys()):
        if a[key] % 2 == 0:
            del a[key]
>>> a
{'b': 3}
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25