2 回答
TA贡献1946条经验 获得超4个赞
看来你需要
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']"}]
TA贡献1811条经验 获得超5个赞
看起来您想转换每个对象,在这种情况下,我会选择具有自定义功能的地图。
import json
dicts = [
{
'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'
}
]
def map_func(item):
item['category'] = {'entity': item['entity'], 'definition': item['definition']}
item.pop('entity')
item.pop('definition')
return item
mapped_dicts = map(lambda x: map_func(x), dicts)
print(json.dumps(list(mapped_dicts), indent=2))
[
{
"name": "Sector",
"synonyms": "Sector:['sector', 'sphere'], , ",
"category": {
"entity": "ORG(100.0)",
"definition": "Sector"
}
},
{
"name": "Community Name",
"synonyms": "Community:['biotic_community', 'community', 'community_of_interests', 'residential_area', 'residential_district']",
"category": {
"entity": "PERSON(39.74)",
"definition": "Community"
}
}
]
添加回答
举报