gpt4 book ai didi

Python - Unnest 字典列表

转载 作者:行者123 更新时间:2023-12-04 10:37:48 24 4
gpt4 key购买 nike

有没有更简洁的 Pythonic 方法来取消嵌套这个字典列表?

示例:

features = [{'annual_sales_revenue': {'definition': 'yearly revenue generated'}}, {'dnb_annual_employees': {'definition': 'number of employees'}}, {'global_industry_hospitality': {'definition': 'in hospitality industry'}}, {'itbuyindex': {'definition': "company's capacity to invest in technology"}}, {'test': {'definition': 'test'}}]

我的解决方案:
{list(f.keys())[0]:f[list(f.keys())[0]]['definition'] for f in features}

预期结果:
{'annual_sales_revenue': 'yearly revenue generated', 'dnb_annual_employees': 'number of employees', 'global_industry_hospitality': 'in hospitality industry', 'itbuyindex': "company's capacity to invest in technology", 'test': 'test'}

最佳答案

您可以使用带有字典理解的双 for 循环:

features = [{'annual_sales_revenue': {'definition': 'yearly revenue generated'}}, {'dnb_annual_employees': {'definition': 'number of employees'}}, {'global_industry_hospitality': {'definition': 'in hospitality industry'}}, {'itbuyindex': {'definition': "company's capacity to invest in technology"}}, {'test': {'definition': 'test'}}]
result = {a:b['definition'] for i in features for a, b in i.items()}

输出:
{'annual_sales_revenue': 'yearly revenue generated', 'dnb_annual_employees': 'number of employees', 'global_industry_hospitality': 'in hospitality industry', 'itbuyindex': "company's capacity to invest in technology", 'test': 'test'}

关于Python - Unnest 字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com