删除字典中的多个键

时间:2019-07-08 16:01:42

标签: python string word-frequency

我有以下简单的python代码:

# 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

我想删除键值不同于“ blonde”的键,但是代码存在以下问题:

1)程序显示错误:

RuntimeError: dictionary changed size during iteration

2)程序将其删除,但只有一个键,即输出为:

{'Brad': 'brown', 'Peter': 'blonde', 'Hanna': 'blonde'},在这种情况下,该程序仅删除 'Jason',但我还需要删除'Brad'

您知道为什么我的代码无法正常工作吗? 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用dict理解:

<select ng-model="award.section.id"
        ng-change="getSectionNominations()" 
        ng-options="object.id as object.section for object in sections")
</select>

<select ng-model="award.nomination.id"
        ng-change="getNominationCategories()"
        ng-options="object.id as object.section for object in nominations") 
</select>

<select ng-model="award.category.id"
        ng-options="object.id as object.section for object in categories"
</select>