Python按值从字典中删除条目

时间:2015-07-27 15:22:26

标签: python json dictionary

我正在尝试从字典中删除不需要的条目。字典看起来像:

 {  "Id":101119     ,"entry1":50009987  ,"entry2":8     ,"entry3":4 }

我的代码是:

import json

value = 2

with open(path, 'r') as json_input:
    unfiltered = json.load(json_input)

for row in unfiltered:
    id = row['Id']
    if row[field] is None:
        del output[id]
    elif int(row[field]) != value:
        del output[id]

但是,我有一个错误:

  

KeyError:101119

我该如何解决?

非常感谢。

1 个答案:

答案 0 :(得分:2)

如果您只知道其值,则无法从字典中删除键值对。一种可能的替代方法是从旧字典创建一个新字典,过滤掉您不想要的值。例如:

d = {4: 8, 15: 16, 23: 42, 99: 8}
d = {key: value for key, value in d.items() if value != 8}
print(d)

结果:

{15: 16, 23: 42}

我不是100%理解你的代码示例,但我希望你能做到:

output = {key: value for key, value in output.items() if value != id}