可能重复:
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
个实例。
答案 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]