python - 对不按顺序排列的字典键和值进行分组
问题描述
下面我有一个字典列表:
dict = [{'name': 'Sector',
'entity': 'ORG(100.0)',
'synonyms': "Sector:['sector', 'sphere'], , ",
'definition': 'Sector'},
{'name': 'Community Name',
'entity': 'PERSON(39.74)',
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
'definition': 'Community'}]
如何添加将实体分组的新键,并将定义定义为值?
所需的输出(类别是新添加的键):
dict = [{'name': 'Sector',
'category': {
'entity': 'ORG(100.0)',
'definition': 'Sector'},
'synonyms': "Sector:['sector', 'sphere'], , "},
{'name': 'Community Name',
'category':{
'entity': 'PERSON(39.74)',
'definition': 'Community'},
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']"}]
我已经尝试过[{'name': i.pop('name'), 'category': i} for I in dict]
,但它只适用于按顺序排列的键,我该如何修改它以便我可以选择某些键,因为entity
它们definition
彼此不相邻?
解决方案
看起来你需要
data = [{'name': 'Sector',
'entity': 'ORG(100.0)',
'synonyms': "Sector:['sector', 'sphere'], , ",
'definition': 'Sector'},
{'name': 'Community Name',
'entity': 'PERSON(39.74)',
'synonyms': "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
'definition': 'Community'}]
subkeys = ['entity', 'definition']
result = [{'category': {k: i.pop(k) for k in subkeys}, **i} for i in data]
print(result)
输出:
[{'category': {'definition': 'Sector', 'entity': 'ORG(100.0)'},
'name': 'Sector',
'synonyms': "Sector:['sector', 'sphere'], , "},
{'category': {'definition': 'Community', 'entity': 'PERSON(39.74)'},
'name': 'Community Name',
'synonyms': "Community:['biotic_community', 'community', "
"'community_of_interests', 'residential_area', "
"'residential_district']"}]
推荐阅读
- python - Python Selenium 给定一个元素,使用 element.find_element 查找直接子元素下面的元素
- java - 如何通过id组合两个对象列表并在kotlin中选择非空值
- python - easyimap - 连接到 gmail 失败,凭据无效
- flutter - 如何在同一个屏幕上两次使用相同标签的英雄?
- python - RQ 调度程序两次排队任务并陷入循环运行排队任务
- html - 使用 css flex 设置 3 列卡
- html - 图像 div 对较小的屏幕尺寸没有响应
- r - 总结列中所有先前的值
- python - 嵌套的 If-else pandas 数据框
- javascript - 如何从数组中删除与另一个数组中的项相等的项?