1

Whenever I run the below code, i receive an error of dictionary changed size during iteration. I am simply trying to put a list into a dictionary with the key being the element inside the list and the value being the count (number of time it appears).

I want the output to be the max value - each value. If the max value is equal to any value inside the dictionary, remove it.

Here is my code:

from collections import Counter


elements=["a", "b", "abc", "c", "a"]

z=Counter(elements)
q=max(z.values()) #get max number

for x in z:
    if z[x] < q:
        z[x] = q-z[x]
    else:
        del z[x] #I am getting an error because of this line of code.
        
print(z)

Any idea on how to get around this error so the output will look like this:

{'b': 1, 'abc': 1, 'c': 1}
Coder123
  • 334
  • 6
  • 26
  • Is it not clear that you get this error because you delete an item from the dictionary while iterating over it? Deleting an item from a dictionary changes the size of the dictionary (it decreases the size by 1). – mkrieger1 Dec 29 '21 at 23:09
  • Make a list of keys you want to delete and delete them after the loop. – Peter Wood Dec 29 '21 at 23:11

1 Answers1

3

You're getting that error because the dictionary changed size while you were iterating over it; this messes up the iterator.

The easy solution is to just make a new dictionary, like this:

z = {x: q - z[x] for x in z if z[x] < q}
Samwise
  • 68,105
  • 3
  • 30
  • 44