[ACCEPTED]-How to filter list of dictionaries with matching values for a given key-filter
Accepted answer
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]
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'}]
>>>
Something like
new_dict = dict((k, v) for k,v in old_dict.items() if v in allowed_values)
?
0
Clean and neat, using filter and lambda
>>> def copyf(dictlist, key, valuelist):
... filter(lambda d: d[key] in valuelist, dictlist)
0
I prefer
filter(lambda d: value in d[key], dictlist)
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.