如何按嵌套字典中comb_indx键的值进行分组?
按comb_indx分组嵌套字典的实现方法
原始数据结构
original_dict = { 'comb_indx': {0: '3925220EE', 1: '3925220EE', 2: '3925220EE', 3: '66478EE', 4: '66478EE', 5: '66478EE', 6: '42300EE', 7: '42300EE', 8: '42300EE'}, 'country': {0: 'EE', 1: 'EE', 2: 'EE', 3: 'EE', 4: 'EE', 5: 'EE', 6: 'EE', 7: 'EE', 8: 'EE'}, 'type': {0: 'CREDIT_ACCOUNT', 1: 'CREDIT_ACCOUNT', 2: 'CREDIT_ACCOUNT', 3: 'SMALL_LOAN', 4: 'SMALL_LOAN', 5: 'SMALL_LOAN', 6: 'SMALL_LOAN', 7: 'SMALL_LOAN', 8: 'SMALL_LOAN'} }
期望输出结构
[ {'comb_indx': '3925220EE', 'country': {0: 'EE', 1: 'EE', 2: 'EE'}, 'type': {0: 'CREDIT_ACCOUNT', 1: 'CREDIT_ACCOUNT', 2: 'CREDIT_ACCOUNT'}}, {'comb_indx': '66478EE', 'country': {3: 'EE', 4: 'EE', 5: 'EE'}, 'type': {3: 'SMALL_LOAN', 4: 'SMALL_LOAN', 5: 'SMALL_LOAN'}}, {'comb_indx': '42300EE', 'country': {6: 'EE', 7: 'EE', 8: 'EE'}, 'type': {6: 'SMALL_LOAN', 7: 'SMALL_LOAN', 8: 'SMALL_LOAN'}} ]
实现代码
使用Python标准库itertools.groupby即可完成分组逻辑,代码如下:
from itertools import groupby original_dict = { 'comb_indx': {0: '3925220EE', 1: '3925220EE', 2: '3925220EE', 3: '66478EE', 4: '66478EE', 5: '66478EE', 6: '42300EE', 7: '42300EE', 8: '42300EE'}, 'country': {0: 'EE', 1: 'EE', 2: 'EE', 3: 'EE', 4: 'EE', 5: 'EE', 6: 'EE', 7: 'EE', 8: 'EE'}, 'type': {0: 'CREDIT_ACCOUNT', 1: 'CREDIT_ACCOUNT', 2: 'CREDIT_ACCOUNT', 3: 'SMALL_LOAN', 4: 'SMALL_LOAN', 5: 'SMALL_LOAN', 6: 'SMALL_LOAN', 7: 'SMALL_LOAN', 8: 'SMALL_LOAN'} } # 先对comb_indx的键值对按值排序,确保groupby能正确分组 sorted_items = sorted(original_dict['comb_indx'].items(), key=lambda x: x[1]) result = [] for key, group in groupby(sorted_items, key=lambda x: x[1]): # 收集当前分组对应的所有索引 indices = [idx for idx, _ in group] # 组装当前分组的字典 group_dict = { 'comb_indx': key, 'country': {idx: original_dict['country'][idx] for idx in indices}, 'type': {idx: original_dict['type'][idx] for idx in indices} } result.append(group_dict) # 输出结果 print(result)
代码说明
groupby仅会将连续的相同值归为一组,因此需要先对comb_indx的键值对按值排序,保证同值项连续- 遍历分组时,先收集该组对应的所有索引,再通过字典推导式从
country和type中提取对应索引的键值对 - 最终将每个分组的字典加入结果列表,即可得到目标结构
内容的提问来源于stack exchange,提问作者Dmytro Kulish
相关产品推荐
相关产品推荐

