开发者

How to filter list of dictionaries with matching values for a given key

With an interface like a = copyf(dictlist, key, valuelist).

>>> dictlist = [{'first': 'James',
              开发者_运维百科   'last': 'Joule'},
                {'first': 'James',
                 'last': 'Watt'},
                {'first': 'Christian',
                 'last': 'Doppler'}]
>>> valuelist = ['James', 'John']
>>> x = copyf(dictlist, 'first', valuelist)
>>> print(x)
[{'first': 'James',
  'last': 'Joule'},
 {'first': 'James',
  'last': 'Watt'}]

The dictlist is effectively a csv.DictReader instance.


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)

?


Clean and neat, using filter and lambda

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


I prefer

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜