[ACCEPTED]-How to filter list of dictionaries with matching values for a given key-filter

Accepted answer
Score: 14

Update: taking into account the reedited question 1 of the OP:

def copyf(dictlist, key, valuelist):
      return [dictio for dictio in dictlist if dictio[key] in valuelist]
Score: 6

Probably not the best solution, but here 1 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'}]
>>> 
Score: 2

Something like

new_dict = dict((k, v) for k,v in old_dict.items() if v in allowed_values)

?

0

Score: 1

Clean and neat, using filter and lambda

>>> def copyf(dictlist, key, valuelist):
...     filter(lambda d: d[key] in valuelist, dictlist)

0

Score: 0

I prefer

filter(lambda d: value in d[key], dictlist)

0

More Related questions