简体   繁体   English

从词典列表中创建词典子集

[英]Create Dictionary subset from list of dictionaries

I have a list of dictionaries that looks like the following: 我有一个字典列表,如下所示:

d = [{'first':'jason','color':'green','age':22},
     {'first':'josh','color':'red','age':22},
     {'first':'chris','color':'blue','age':21}
    ]

I want to create a dictionary that is a subset of the previous dictionaries. 我想创建一个字典,它是以前字典的一个子集。

Something that looks like: 看起来像:

newD = {'jason':22, 'josh':22, 'chris':21}

The following does the trick: 以下是诀窍:

first = [k['first'] for k in d]
age = [k['age'] for k in d]
newD = dict(zip(first, age))

But is there a more Pythonic/cleaner way to do this? 但有没有更多Pythonic /更清洁的方法来做到这一点?

newd = {dd['first']: dd['age'] for dd in d}

Output: 输出:

In [3]: newd
Out[3]: {'chris': 21, 'jason': 22, 'josh': 22}

Yes, you only need one comprehension: 是的,你只需要一个理解:

>>> {x['first']: x['age'] for x in d}
{'jason': 22, 'josh': 22, 'chris': 21}

也许这个?

newD = dict((x['first'], x['age']) for x in d)

Using operator.itemgetter : 使用operator.itemgetter

from operator import itemgetter

res = dict(map(itemgetter('first', 'age'), d))

{'jason': 22, 'josh': 22, 'chris': 21}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM