0

I have the following simple python code:

# Dictionary of strings and int
wordFreqDic = {
    "Hanna": "blonde",
    "Brad" : "brown" ,
    "Peter" : "blonde",
    "Jason" : "brown"
    }

#If key exist in dictionary then delete it using del.

def answer():
    for i in wordFreqDic:
        if wordFreqDic[i]=="blonde":
            print("ok")
        else:
            del wordFreqDic[i]
    return wordFreqDic

I wanted to remove keys that have as values different to "blonde", but the problems with the code are:

1) The program gives the error:

RuntimeError: dictionary changed size during iteration

2) The program removes it, but only one key, i.e, the output is:

{'Brad': 'brown', 'Peter': 'blonde', 'Hanna': 'blonde'}, in this case the program remove only'Jason', but I need remove also 'Brad'.

Do you have some idea why my code is not working properly? Thanks for your help.

Lorenzo Castagno
  • 528
  • 1
  • 10
  • 27
  • Every time you iterate over a mutable data structure, do not change it _white you are iterating_. First, get all keys you want removed, and just then, after iteration is finished, you remove em – rafaelc Jul 08 '19 at 16:04

1 Answers1

0

You can use dict comprehensions:

updated_dict = {k:v for k,v in wordFreqDic.items() if v != "blonde"}
Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39