python - 如何从字典列表中获取值为此创建一个函数
问题描述
我有字典,其中有字典列表
字典列表有另一个字典列表
我需要提取值并将其附加到列表中
我需要写一个函数。如果孩子有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)
我的输出没有提取并放入列表?
解决方案
这是一个可能的解决方案:
result = [{'id': d['id'], 'Area': [nd['name'] for nd in d['Area']]} for d in a]
推荐阅读
- javascript - Javascript修改CSS时的CSS特异性?
- android - How to make checked button at BottomNavigationMenu?
- python-sphinx - How to create custom admonitions in custom directive sphinx?
- javascript - Socket.io only work sometimes and is sharing emit
- asp.net - DropDownList in MVC asp.net
- arrays - 如何将json数据中的复杂字符串转换为数组
- python-3.x - Selenium 的连接问题 - Python
- python - Python pptx 模块相关
- arrays - Building nested TreeNode array in Typescript
- java - REST API 测试用例失败,同样在 POSTMAN 中通过