开发者

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

开发者 https://www.devze.com 2023-02-28 02:38 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Copy dictionaries with matching values for a given key
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

精彩评论

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