How to filter list of dictionaries with matching values for a given key
Update: taking into account the reedited question of the OP:
def copyf(dictlist, key, valuelist):
return [dictio for dictio in dictlist if dictio[key] in valuelist]
Probably not the best solution, but here we go:
>>> def copyf(data, key, allowed):
... return filter(lambda x: key in x and x[key] in allowed, data)
...
>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> copyf(dictlist, 'first', ('Christian',))
[{'last': 'Doppler', 'first': 'Christian'}]
>>> copyf(dictlist, 'last', ('Christian',))
[]
>>> copyf(dictlist, 'first', ('James',))
[{'last': 'Joule', 'first': 'James'}, {'last': 'Watt', 'first': 'James'}]
>>>
Something like
new_dict = dict((k, v) for k,v in old_dict.items() if v in allowed_values)
?