简体   繁体   中英

[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.
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.

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:

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 :

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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