I have a list of dictionaries that have the same keys within eg:
[{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....]
I'm trying to delete k1 from all dictionaries within the list.
I tried
map(lambda x: del x['k1'], list)
but that gave me a syntax error. Where have I gone wrong?
Method 1: Remove a Key from a Dictionary using the del The del keyword can be used to in-place delete the key that is present in the dictionary in Python.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary.
Python Dictionary clear() MethodThe clear() method removes all the elements from a dictionary.
lambda bodies are only expressions, not statements like del
.
If you have to use map and lambda, then:
map(lambda d: d.pop('k1'), list_of_d)
A for loop is probably clearer:
for d in list_of_d:
del d['k1']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With