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.