简体   繁体   English

从嵌套字典/ json中删除键

[英]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? 有人可以给我指点吗?

The error 错误

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")
    ...

A better approach 更好的方法

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.

相关问题 在Python中从Dictionary删除键 - Deleting a key from Dictionary in Python Python嵌套字典添加json中的key:values - Python nested dictionary add key:values from json 如何从嵌套字典中提取键值对并在json中输出 - How to extract a key value pair from a nested dictionary and output it in json 删除嵌套字典中的键值对并找到键值的总和 - deleting a key value pair in nested dictionary and finding the sum of key values 从词典列表中的词典中删除键 - Deleting a key from a dictionary that is in a list of dictionaries Python/JSON 当你有嵌套字典中的键时,在字典中获取值? - Python/JSON Getting values in a dictionary, when you have the key from a nested dictionary? JSON获取嵌套字典中的关键路径 - JSON get key path in nested dictionary 从字典中删除键,但键存在时Python中的KeyError - KeyError in Python when deleting a key from dictionary, but key exists 如何遍历嵌套字典(来自 json)并检查键是否在另一个嵌套字典(来自 json)中,如果不是则添加? - How do I loop through nested dictionaries (from json) and check if key is in another nested dictionary (from json), and add if not? 有人如何通过JSON文件中的嵌套数组在python中多行创建python key:value字典? - How can someone create a python key:value dictionary from a nested array in a JSON file with multiple lines in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM