根据匹配的键:值对在嵌套字典列表中组合嵌套字典

2024-10-04 11:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在谷歌上搜索,发现了一个与我的用例非常相似的问题:combine dictionaries in list of dictionaries based on matching key:value pair。但它似乎并没有100%符合我的情况,因为我有嵌套字典列表。假设我有一个嵌套字典列表(多于2个),但在本例中,我考虑使用两个嵌套字典作为示例:

my_list = [{'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [{'mention': [27, 28],
    'positives': [26278, 27735, 21063],
    'negatives': [],
    'entity': 27735}]},
 {'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [{'mention': [13, 14],
    'positives': [7654],
    'negatives': [],
    'entity': 7654}]}]

如何根据键(句子)和值(所有标记的列表)的匹配来合并这两个词典,以便得到如下所示的结果:

my_new_list = [
{'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [
    {'mention': [27, 28],
    'positives': [26278, 27735, 21063],
    'negatives': [],
    'entity': 27735
    },
   {'mention': [13, 14],
    'positives': [7654],
    'negatives': [],
    'entity': 7654
     }
   ]
}
]

如何在匹配键(句子):值(所有标记的列表)时合并键“提及”列表?在我的实际列表中,将有许多相同风格的词典

非常感谢你的帮助


Tags: 列表字典sentencelistusedentityhasbeen
2条回答
my_dict = {}
for row in my_list:
    key = ' '.join(row['sentence']) # use sentence as key
    if key in my_dict:
        my_dict[key]['mentions'].extend(row['mentions'])
    else:
        my_dict[key] = row
        
my_list = list(my_dict.values())

据我所知,您希望按“句子”对信息进行分组

您可以通过迭代数组并填充按句子索引的列表字典来实现这一点

比如:

from collections import defaultdict
sentences = defaultdict(list)
for element in my_list:
   key = tuple(element["sentence"])
   sentences[key].append(element)

这给你

 { sentence1: [element1, element2], sentence2: [element3] }

从那里应该能够轻松地构建您想要的结构

编辑删除对特定字段的引用

相关问题 更多 >