如何将列表中给定键的匹配值的字典复制到新列表?

时间:2011-04-23 20:45:08

标签: python

  

可能重复:
  Copy dictionaries with matching values for a given key

使用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'}]

dictlist实际上是csv.DictReader个实例。

2 个答案:

答案 0 :(得分:3)

x = [d for d in dictlist if d['first'] in valuelist]

答案 1 :(得分:0)

此备选方案返回字典的副本:

def copyf(dictlist, key, valuelist)
        return [copy.deepcopy(dictio) for dictio in dictlist if dictio[key] in valueList]