Search code examples
pythonlist-comprehension

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


Solution

  • If you really want to use a list comprehension, combine it with a dict comprehension:

    [{k: v for k, v in d.iteritems() if k != 'mykey1'} for d in mylist]
    

    Substitute .iteritems() for .items() if you are on python 3.

    On python 2.6 and below you should use:

    [dict((k, v) for k, v in d.iteritems() if k != 'mykey1') for d in mylist]
    

    as the {key: value ...} dict comprehension syntax was only introduced in Python 2.7 and 3.