How to copy dictionaries with matching values for a given key from list to new list? [duplicate]
Possible Duplicate:
Copy 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.
x = [d for d in dictlist if d['first'] in valuelist]
This alternative returns a copy of the dictionaries:
def copyf(dictlist, key, valuelist)
return [copy.deepcopy(dictio) for dictio in dictlist if dictio[key] in valueList]
精彩评论