[英]Deleting a key from a nested dictionary / json
I am trying to remove an element from a JSON file using python. 我正在尝试使用python从JSON文件中删除元素。 I have converted the dictionary to a python dictionary and so far I have been failing. 我已将字典转换为python字典,到目前为止,我一直失败。 JSON file I am working with is uploaded here 我正在使用的JSON文件在此处上传
I need to delete all the associated keys and value from the JSON if the key is 'access_ip_v4'
. 如果密钥是'access_ip_v4'
我需要从JSON中删除所有关联的密钥和值。
I cannot use sed/grep or any other regex techniques or string replace techniques. 我不能使用sed / grep或任何其他正则表达式技术或字符串替换技术。 I am kind of stuck with python dictionaries on this. 我对此有点迷恋于python字典。
Here is my work so far. 到目前为止,这是我的工作。
def dict_sweep(input_dic, k):
for key in input_dic.keys():
if key == k:
print("DIRECT DELETE")
del input_dic[key]
elif type(input_dic[key]) is dict:
print('DICT FOUND')
input_dic[key] = dict_sweep(input_dic[key], k)
elif isinstance(type(input_dic[key]), type([])):
print("LIST FOUND")
for i, v in enumerate(input_dic[key]):
if isinstance(input_dic[key][i], dict):
input_dic[key][i] = dict_sweep(v, k)
return input_dic
I think my code fails when it encounters a list. 我认为我的代码在遇到列表时失败。 Failing in the sense, 在某种意义上失败了,
clean_data = dict_sweep(data, 'access_ip_v4')
print(clean_data)
will again print the data
rather than printing the cleaned version of data. 将再次打印data
而不是打印data
的清理版本。
I am not so sure about it. 我不太确定。 I have read some other questions like this but It is not helpful. 我已阅读像其他一些问题, 这却是无益的。 Can someone give me a pointer here? 有人可以给我指点吗?
Your error comes from the expression isinstance(type(input_dic[key]), type([]))
. 您的错误来自表达式isinstance(type(input_dic[key]), type([]))
。 You want to check if input_dict[key]
is a list, not type(input_dic[key])
which is a type. 您要检查input_dict[key]
是否为列表,而不是type(input_dic[key])
。
So replace the last elif
statement by this. 因此,以此替换最后一个elif
语句。
elif isinstance(input_dic[key], list):
print("LIST FOUND")
...
Although, it is not recommended to delete from the object you are iterating over. 虽然,不建议从要迭代的对象中删除。 In particular, if you are using Python3, the above code will raise RuntimeError: dictionary changed size during iteration
. 特别是,如果您使用的是Python3,则上面的代码将引发RuntimeError: dictionary changed size during iteration
。 The correct approach is to build a new dictionary without the keys you want to delete. 正确的方法是在没有要删除的键的情况下构建新词典。
def dict_sweep(input_dict, key):
if isinstance(input_dict, dict):
return {k: dict_sweep(v, key) for k, v in input_dict.items() if k != key}
elif isinstance(input_dict, list):
return [dict_sweep(element, key) for element in input_dict]
else:
return input_dict
Here is the result. 这是结果。
d = {'delete': 1, 'ok': [{'delete': 1, 'ok': 1}]}
new_d = dict_sweep(d, 'delete') # {'ok': [{'ok': 1}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.