Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing key values pairs from a list of dictionaries

I have a list of dictionaries such as:

[{'mykey1':'myvalue1', 'mykey2':'myvalue2'}, {'mykey1':'myvalue1a', 'mykey2':'myvalue2a'}]

I need to remove all key values pairs from all dictionaries where the key is equal to mykey1. I could do this by looping through and using the del statement, but I am wondering how I would create a new list using list comprehensions or lambdas which would just remove all key value pairs where the key was mykey1.

Many thanks

like image 307
dublintech Avatar asked Nov 06 '12 15:11

dublintech


People also ask

Can you remove key-value pairs from a dictionary?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method.

How do I remove a key from a dictionary list?

Method #1 : Using loop + del The combination of above functions can be used to solve this problem. In this, we iterate for all the keys and delete the required key from each dictionary using del.


1 Answers

[d.pop('mykey1', None) for d in list]

like image 170
Cameron Sparr Avatar answered Oct 21 '22 07:10

Cameron Sparr