我正在尝试从字典中删除列表中某些JSON部分的{'settings':'Val'},我可以使用var ['a'] ['b'] [2]进行删除但是我想通过遍历“ b”来删除“设置”
删除“设置”的方法是什么?
var = {
'a': {
'b': [
{
'check': 'val'
},
{
'alerts': 'val'
},
{
'settings': 'val'
}
]
}
}
for items in var['a']['b']:
del items['settings']
Traceback (most recent call last):
File "/Users/sree/PycharmProjects/test/app1.py", line 59, in <module>
del items['settings']
KeyError: 'settings
## tried this and getting the same error
for items in var['a']['b']:
items.pop('settings')
print(var)
Traceback (most recent call last):
File "/Users/sree/PycharmProjects/test/app1.py", line 70, in <module>
items.pop('settings')
KeyError: 'settings'
答案 0 :(得分:0)
您可以使用列表理解来过滤字典:
var = {
'a': {
'b': [
{
'check': 'val'
},
{
'alerts': 'val'
},
{
'settings': 'val'
}
]
}
}
var['a']['b'] = [val for val in var['a']['b'] if 'settings' not in val]
import json
print(json.dumps(var, indent=4))
打印:
{
"a": {
"b": [
{
"check": "val"
},
{
"alerts": "val"
}
]
}
}