简体   繁体   中英

Deleting a key from a dictionary that is in a list of dictionaries

I have a list of dictionaries generated by:

    r=requests.get(url, headers={key:password})
    import_data_list.append(r.json())

I want to delete the first key from these dictionaries. I know I can delete the dictionaries in the list with:

    del import_data_list[0]

But how do I delete a key from the dictionary in the list, rather than deleting the whole dictionary.

I tried something like:

    del import_data_list[0["KEY"]]

Obviously it doesnt work!

Any help would be much appreciated and sorry if its a dumb question. Still learning!

If you want to delete the first key (you don't know its name, you just know it is the first one) from these dictionaries, I suggest you to loop over the dictionaries of the list. You can use list(d.keys())[0] or even list(d)[0] to get the first key of a dictionary called d .
Here is an example:

for d in import_data_list:
    k = list(d)[0]  # get the first key
    del d[k]        # delete it from the dictionary
print(import_data_list)

You can also do it with one-lined style using a list comprehension, which I find quite smart too. In this case you also retrieve the values of the first keys in a list, which might be useful:

r = [d.pop(list(d)[0]) for d in import_data_list]
print(import_data_list)

Note that it works only with python version >= 3.6 (but not with version <= 3.5 because dictionaries are not ordered)

Assume you have this list of dictionaries.

myList = [
    {
        "Sub1List1" : "value",
        "Sub2List1" : "value",
        "Sub3List1" : "value",
        "Sub4List1" : "value"
    },
    {
        "Sub1List2" : "value",
        "Sub2List2" : "value",
        "Sub3List2" : "value",
        "Sub4List2" : "value"
    },
    {
        "Sub1List3" : "value",
        "Sub2List3" : "value",
        "Sub3List3" : "value",
        "Sub4List3" : "value"
    }
]

Now, if you want to delete key Sub1List1 from the first list, you can do this by using :

del myList[0]["Sub1List1"]

使用命令:

del dictionaryName[KEY]

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