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
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.
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.
[d.pop('mykey1', None) for d in list]
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