python - 从字典列表创建字典子集

标签 python dictionary

我有一个字典列表,如下所示:

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

我想创建一个字典,它是以前字典的子集。

看起来像的东西:

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

下面的技巧:

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

但是有没有更 Pythonic/cleaner 的方法来做到这一点?

最佳答案

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

输出:

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

关于python - 从字典列表创建字典子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52230160/

相关文章:

python - 解析列表中的 Python 字典

python - 内联函数的字典理解

python - 将字典列表转换为 Pandas 数据框

python - 如何从 Python 脚本中运行 Streamlit 应用程序?

python - Python 和 C 之间独立于操作系统的程序间通信

python - FaceNet 嵌入的余弦距离问题

python - Ansible kitchen 测试在 debian 上执行源命令失败

python - Apache 不会运行 Py_Initialize();功能

c# - 理解字典,使用c#向字典添加新值

python - 使用字典查找 df 的两列值的模式并基于该模式添加新列