如何解决如何在字典列表中分组和添加字典键
下面有一个词典列表:
dict = [{'name': 'Sector','entity': 'ORG(100.0),nan,nan','synonyms': "Sector:['sector','sphere'],",'definition': 'Sector: a plane figure bounded by two radii and the included arc of a circle','sentiment': ''},{'name': 'Community Name','entity': 'PERSON(39.74),GPE(22.88),ORG(20.57),LOC(9.95),FAC(3.6),NORP(2.02),CARDINAL(0.45),LAW(0.39),DATE(0.39),'synonyms': "Community:['biotic_community','community','community_of_interests','residential_area','residential_district'],Name:['advert','appoint','bring_up','call','cite','constitute','describe','diagnose','discover','distinguish','epithet','figure','gens','identify','key','key_out','list','make','mention','name','nominate','public_figure','refer'],'definition': 'Community: a group of people living in a particular local area,Name: a language unit by which a person or thing is known','sentiment': ''}]
如何添加将实体,同义词,定义和情感分组为值的新键?
所需的输出(nlp是新添加的键):
dict = [{'name': 'Sector','nlp': {
'entity': 'ORG(100.0),'sentiment': ''}},'nlp':{
'entity': 'PERSON(39.74),'sentiment': ''}}]
解决方法
您可以在for循环中使用.pop()
:
lst = [{'name': 'Sector','entity': 'ORG(100.0),nan,nan','synonyms': "Sector:['sector','sphere'],",'definition': 'Sector: a plane figure bounded by two radii and the included arc of a circle','sentiment': ''},{'name': 'Community Name','entity': 'PERSON(39.74),GPE(22.88),ORG(20.57),LOC(9.95),FAC(3.6),NORP(2.02),CARDINAL(0.45),LAW(0.39),DATE(0.39),'synonyms': "Community:['biotic_community','community','community_of_interests','residential_area','residential_district'],Name:['advert','appoint','bring_up','call','cite','constitute','describe','diagnose','discover','distinguish','epithet','figure','gens','identify','key','key_out','list','make','mention','name','nominate','public_figure','refer'],'definition': 'Community: a group of people living in a particular local area,Name: a language unit by which a person or thing is known','sentiment': ''}]
result = []
for dct in lst:
newdict = {}
newdict["name"] = dct.pop('name')
newdict["nlp"] = dct
result.append(newdict)
print(result)
哪个产量
[{'name': 'Sector','nlp': {'entity': 'ORG(100.0),'sentiment': ''}},'nlp': {'entity': 'PERSON(39.74),'sentiment': ''}}]
,
pop()
删除一个元素并返回该元素
result = [{'name':d.pop('name'),'nlp':d} for d in dict]
通过使用专有密钥name
,我们从d
中删除了该密钥。如前所述,d.pop('name')
将返回d['name']
d.pop('name')
之后,d
中将没有密钥name
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。