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 diction
Solution 1:
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 keydel d[k] # delete it from the dictionaryprint(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)
Solution 2:
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"]
Solution 3:
Use the command:
del dictionaryName[KEY]
Post a Comment for "Deleting A Key From A Dictionary That Is In A List Of Dictionaries"