如何用字典/列表推导式将字典列表转为按pay分组的嵌套字典
字典列表转嵌套字典的实现方案
原始数据
data=[{'first': '0', 'last': 'hg01', 'pay': 0}, {'first': '0', 'last': 'hg75', 'pay': 15}, {'first': '0', 'last': 'hg0', 'pay': 1}, {'first': '0', 'last': 'hg9', 'pay': 13}, {'first': '0', 'last': 'hg0', 'pay': 0}, {'first': '0', 'last': 'hg', 'pay': 13}, {'first': '0', 'last': 'hg76', 'pay': 0}, {'first': '0', 'last': 'hg1', 'pay': 9}, {'first': '0', 'last': 'hg81', 'pay': 13}, {'first': '0', 'last': 'hg12', 'pay': 1}, {'first': '0', 'last': 'hg03', 'pay': 15}, {'first': '0', 'last': 'hg11', 'pay': 9}, {'first': '0', 'last': 'hg1', 'pay': 1}]
目标输出
output={0: {'hg76':{'first': '0'},'hg0':{'first': '0'},'hg01':{'first': '0'}}, 15: {'hg75':{'first': '0'},'hg03':{'first': '0'}}, 1: {'hg1':{'first': '0'},'hg12':{'first': '0'},'hg0':{'first': '0'}}, 13: {'hg81':{'first': '0'},'hg':{'first': '0'},'hg9':{'first': '0'}}, 9: {'hg1':{'first': '0'},'hg11':{'first': '0'}}}
实现方法
方法一:高效遍历分组(推荐)
用collections.defaultdict辅助分组,只需遍历一次原始数据:
from collections import defaultdict result = defaultdict(dict) for item in data: pay_val = item['pay'] last_val = item['last'] result[pay_val][last_val] = {'first': item['first']} # 可选:转换为普通字典 output = dict(result)
方法二:纯字典推导式实现
完全用推导式语法完成转换,适合偏好简洁写法的场景:
output = { pay: { item['last']: {'first': item['first']} for item in data if item['pay'] == pay } for pay in {item['pay'] for item in data} }
说明
- 方法一效率更高,仅遍历一次数据,适合处理大规模数据集;
- 方法二用推导式实现,代码更紧凑,但会为每个
pay值重复遍历数据,数据量大时性能稍逊。
内容的提问来源于stack exchange,提问作者حسین سلطانی
相关产品推荐
相关产品推荐

