开发者

How to copy dictionaries with matching values for a given key from list to new list? [duplicate]

This question already has answers here: Closed 11 years ago.

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]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜