【问题标题】:How to remove key-value pairs from a dictionary where the key matches an item in a list?如何从键与列表中的项目匹配的字典中删除键值对?
【发布时间】:2021-12-05 04:53:36
【问题描述】:

我有一本像这样的字典

my_dict = {'i': 5, 'citizens': 12, 'you': 344, 'the': 567, 'me': 11, 'states': 22, '': 104, 'in': 156} 

还有一个看起来像的列表

ignore_words = ['i', 'we', 'you', 'he', 'she', 'it', 'they', 'me', 'us']

我想编辑字典以删除其中一个键与列表中的某个项目匹配的所有键值对,因此我的输出如下所示:

my_dict = {'citizens': 12, 'the': 567, 'states': 22, '': 104, 'in': 156} 

我试过了

[my_dict.pop(key) for key in ignore_words]

但我得到了KeyError。 最好的方法是什么?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    您可以在dict.keys 上使用set.differenceignore_list

    keys = my_dict.keys() - ignore_words
    out  = {k: my_dict[k] for k in keys}
    # {'': 104, 'in': 156, 'states': 22, 'citizens': 12, 'the': 567}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2015-12-27
      相关资源
      最近更新 更多