简体   繁体   English

从JSON字典中删除项目会留下一个空的字典:“ {}”。 如何将其完全删除?

[英][del]eting an item from a JSON dictionary leaves an empty dict: `{}`. How do I remove it completely?

I am trying to delete a dictionary item nested within a list, in a dict. 我正在尝试删除字典中嵌套在列表中的字典项。
After I del the object, the modified dictionary will contain an empty dictionary: {} in the place of the deleted object. del对象之后,修改后的字典将包含一个空字典: {}代替删除的对象。
Here is the code I am using: 这是我正在使用的代码:

json_dict = {"top_key": "top_value", "bottom_key": [{"list_dict": "list_dict_value"},{"list_dict1": "list_dict_value1"}]}

print("initial:", json_dict)

def delete(list_dict):
    for i in json_dict["bottom_key"]:
        if list_dict in i:
            del i[list_dict]


delete("list_dict")
print("final:", json_dict)  

The final print will return: 最终打印将返回:
final: {'bottom_key': [{}, {'list_dict1': 'list_dict_value1'}], 'top_key': 'top_value'} (pw-retriever) simon@[pw-retriever](fix_del_ls)

I am trying to find a way to remove the {} in addition to the key:value pair, in one go. 我正在尝试找到一种方法来一次性删除{}和key:value对。

edit: an explanation as to what the heck is going on would also be highly appreciated. 编辑:关于到底发生了什么的解释也将不胜感激。

You can do the following: 您可以执行以下操作:

for i in json_dict["bottom_key"][:]:  # important: iterate a shallow copy
    if list_dict in i:
        json_dict["bottom_key"].remove(i)

However, since removing from a list is O(N) and you might have to remove multiple elements, you might consider just rebuilding it from scratch in one go: 但是,由于从列表中删除是O(N)并且您可能必须删除多个元素,因此您可以考虑一次性从头开始重建它:

json_dict["bottom_key"] = [d for d in json_dict["bottom_key"] if list_dict not in d]

Constructing further on basis of your structure, del using the index of the dict , like follows : 根据您的结构进一步构建,使用dict的索引进行del ,如下所示:

def delete(list_dict):
    for i,ele in enumerate(json_dict["bottom_key"][:]) :
        if list_dict in ele:
            del json_dict["bottom_key"][i]

#driver values : #driver值:

IN : initial: {'top_key': 'top_value', 'bottom_key': [{'list_dict': 'list_dict_value'}, {'list_dict1': 'list_dict_value1'}]}

>>> delete("list_dict")

OUT : final: {'top_key': 'top_value', 'bottom_key': [{'list_dict1': 'list_dict_value1'}]}

EDIT : schwobaseggl's idea of reconstructing the dictionary is better than deleting the elements as the previous one can lead to logical mistakes. 编辑: schwobaseggl重建字典想法比删除元素更好,因为前一个元素会导致逻辑错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM