首页 > 解决方案 > 对不按顺序排列的字典键和值进行分组

问题描述

下面我有一个字典列表:

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彼此不相邻?

标签: pythondictionary

解决方案


看起来你需要

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']"}]

推荐阅读