Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting key/value from list of dictionaries using lambda and map

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?

like image 323
webley Avatar asked Dec 09 '09 18:12

webley


People also ask

How do I remove a key from a dictionary list?

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.

What method can be used to remove and return an arbitrary key value item pair from the dictionary?

The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary.

Can I use Clear () method to delete the dictionary?

Python Dictionary clear() MethodThe clear() method removes all the elements from a dictionary.


1 Answers

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']
like image 74
Ned Batchelder Avatar answered Oct 04 '22 18:10

Ned Batchelder