Removing key values pairs from a list of dictionaries
def new_dict(old_dict):
n = old_dict.copy()
n.pop('mykey1',None)
return n
new_list_of_dict = map(new_dict,list_of_dict)
or
new_list_of_dict = [ new_dict(d) for d in list_of_dict ]
Rather than using del
, I opted for dict.pop
since pop
will suppress the KeyError
if the key doesn't exist.
If you really only want to get certain keys, this becomes a bit easier.
from operator import itemgetter
tuple_keys = ('key1','key2','key3')
get_keys = itemgetter(*tuple_keys)
new_dict_list = [ dict(zip(tuple_keys,get_keys(d)) for d in old_dict_list ]
which raises KeyError
if the keys aren't in the old dict
Or:
new_dict_list = [ dict( (k,d.get(k,None)) for k in tuple_keys ) for d in old_dict_list ]
which will also add key:None
if key
isn't in the old dict. If you don't want that None
, you could do:
new_dict_list = [ dict( (k,d[k]) for k in tuple_keys if k in d) for d in old_dict_list ]
Depending on what percent of the dictionary you're including/excluding and the size of the dictionaries, this might be slightly faster than the solution by @MartijnPieters.
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.
[d.pop('mykey1', None) for d in list]