首页 > 解决方案 > 如何从字典列表中获取值为此创建一个函数

问题描述

我有字典,其中有字典列表

我需要写一个函数。如果孩子有name追加到父列表,以便任何字典通过函数列表将创建一个输出,如下所示

a = [{"id": "1", "Area": [{"id": "2", "name": "Clinical"},
                          {"id": "23", "name": "Delivery"}]},
     {"id": "2", "Area": [{"id": "2", "name": "Clinical"},
                          {"id": "23", "name": "Delivery"}]}]

预期输出:

[{"id": "1", "Area": ["Clinical", "Delivery"]},
 {"id": "2", "Area": ["Clinical", "Delivery"]}]

代码如下

result = []
temp = {}
for i in range(0,len(a)):
    templist = []
    b = a[i]['Area'][i]['name']
    c = a[i]['id']
    temp['id'] = c
    templist.append(b)
    temp['Area'] = templist
    result.append(temp)
    print (result)

我的输出没有提取并放入列表?

标签: pythondictionary

解决方案


这是一个可能的解决方案:

result = [{'id': d['id'], 'Area': [nd['name'] for nd in d['Area']]} for d in a]

推荐阅读