18

I want pop out all the large values and its keys in a dictionary, and keep the smallest. Here is the part of my program

for key,value in dictionary.items():
    for key1, value1 in dictionary.items(): 
            if key1!= key and value > value1:
                dictionary.pop(key)             
    print (dictionary)  

Which results in

RuntimeError: dictionary changed size during iteration    

How can I avoid this error?

8
  • 1
    You need to create another dictionary and move the elements to that dict.
    – Rohit Jain
    Commented Nov 22, 2012 at 20:34
  • I thought about to create a new empty dictinary and move the smallest item in it, but I still have the same problem
    – YXH
    Commented Nov 22, 2012 at 20:35
  • Can you use an another method than pop ?
    – Zulu
    Commented Nov 22, 2012 at 20:37
  • I tried that way, but the program would have a key error.
    – YXH
    Commented Nov 22, 2012 at 20:37
  • 1
    Please update your question with an example of this dictionary, and a mockup of the desired results.
    – yurisich
    Commented Nov 22, 2012 at 20:43

9 Answers 9

15

Alternative solutions

If you're looking for the smallest value in the dictionary you can do this:

min(dictionary.values())

If you cannot use min, you can use sorted:

sorted(dictionary.values())[0]

Why do I get this error?

On a side note, the reason you're experiencing an Runtime Error is that in the inner loop you modify the iterator your outer loop is based upon. When you pop an entry that is yet to be reached by the outer loop and the outer iterator reaches it, it tries to access a removed element, thus causing the error.
If you try to execute your code on Python 2.7 (instead of 3.x) you'll get, in fact, a Key Error.

What can I do to avoid the error?

If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.

7
  • 2
    the op question is: "How to solve dictionary changed size during iteration in Python" Commented Apr 10, 2015 at 11:02
  • Yes, OP asked "how do I avoid this error?" and this answer contains a couple of alternatives for actually doing what they were trying to do, an explanation of the reason why the error was happening and how to solve it if you really want to use a straight loop (see the very last sentence). Commented Apr 10, 2015 at 11:30
  • you are right, sorry. Please make small edit, so that I could vote back. Commented Apr 10, 2015 at 11:35
  • @minerals Ok, I've added some headings to hopefully make the answer more understandable Commented Apr 10, 2015 at 12:34
  • 1
    If you want to modify a dict, while iterating on it, you can do for key in list(d): del d[key] . You are now iterating on a list, not a reference to the dict itself. That's why you can't just iterate on dict.keys(), because it's a reference to the actual dict.
    – ninMonkey
    Commented Aug 21, 2019 at 13:14
15

In Python3, Try

for key in list(dict.keys()):
    if condition:
        matched
        del dict[key]

1 more thing should be careful when looping a dict to update its key:

Code1:

keyPrefix = ‘keyA’
for key, value in Dict.items():
    newkey = ‘/’.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Code2:

keyPrefix = ‘keyA’
for key, value in Dict.keys():
    newkey = ‘/’.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Result of code1/code2 is:

{‘keyA/keyA/keyB’ : ”, ‘keyA/keyA/keyA’: ”}

My way to resolve this unexpected result:

    Dict = {‘/’.join([keyPrefix, key]): value for key, value in Dict.items()}

Link: https://blog.gainskills.top/2016/07/21/loop-a-dict-to-update-key/

0
7

You can use copy.deepcopy to make a copy of the original dict, loop over the copy while change the original one.

from copy import deepcopy

d=dict()
for i in range(5):
    d[i]=str(i)

k=deepcopy(d)

d[2]="22"
print(k[2])
#The result will be 2.

Your problem is iterate over something that you are changing.

1
  • 4
    d.copy() will do the same
    – Ahmad
    Commented May 16, 2018 at 7:39
2

Record the key during the loop and then do dictionary.pop(key) when loop is done. Like this:

for key,value in dictionary.items():
    for key1, value1 in dictionary.items(): 
            if key1!= key and value > value1:
                storedvalue = key
    dictionary.pop(key)  
2
  • but it still change the size.
    – YXH
    Commented Nov 22, 2012 at 20:47
  • Then store keys in list. And remove all dictionary items after both loops are done. Commented Nov 22, 2012 at 20:50
2

Here is one way to solve it:

  1. From the dictionary, get a list of keys, sorted by value
  2. Since the first key in this list has the smallest value, you can do what you want with it.

Here is a sample:

# A list of grades, not in any order
grades = dict(John=95,Amanda=89,Jake=91,Betty=97)

# students is a list of students, sorted from lowest to highest grade
students = sorted(grades, key=lambda k: grades[k])

print 'Grades from lowest to highest:'
for student in students:
    print '{0} {1}'.format(grades[student], student)

lowest_student = students[0]
highest_student = students[-1]
print 'Lowest grade of {0} belongs to {1}'.format(grades[lowest_student], lowest_student)
print 'Highest grade of {0} belongs to {1}'.format(grades[highest_student], highest_student)

The secret sauce here is in the sorted() function: instead of sorting by keys, we sorted by values.

0

If you want to just keep the key with the smallest value, I would do it by first finding that item and then creating a new dictionary containing only it. If your dictionary was d, something like this would do that in one line:

d = dict((min(d.items(), key=lambda item: item[1]),))

This will not only avoid any issues about updating the dictionary while iterating it, it is probably faster than removing all the other elements.

If you must do the modifications in-place for some reason, the following would work because it makes a copy of all the keys before modifying the dictionary:

key_to_keep = min(d.items(), key=lambda item: item[1])[0]

for key in list(d):
    if key != key_to_keep:
        d.pop(key)
0

As I read your loop right now, you're looking to keep only the single smallest element, but without using min. So do the opposite of what your code does now, check if value1 < minValueSoFar, if so, keep key1 as minKeySoFar. Then at the end of the loop (as Zayatzz suggested), do a dictionary.pop(minKeySoFar)

As an aside, I note that the key1!=key test is irrelevant and computationally inefficient assuming a reasonably long list.

minValueSoFar = 9999999;   # or whatever
for key,value in dictionary.items():
    if value < minValueSoFar:
        minValueSoFar = value
        minKeySoFar = key
dictionary.pop(minKeySoFar)   # or whatever else you want to do with the result
0

An alternative solution to dictionary changed size during iteration:

for key,value in list(dictionary.items()):
    for key1, value1 in list(dictionary.items()): 
            if key1!= key and value > value1:
                dictionary.pop(key)             
print (dictionary)  

Better use it with caution! when using this type of code, because list(dictionary.items()) calculated when the complier enters first time to loop. Therefore any change made on dictionary won't affect process inside the current loop.

0

You could create a list with the vaules you want to delete and than run a second for loop:

for entry in (listofkeystopop):
        dictionary.pop(entry)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.