You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用sorted()函数对嵌套字典的子字典按键排序?

解决嵌套字典的子字典按键排序问题

原字典(修正笔误后):

dict1 = {1: {7: [6], 1: [7]}, 2: {3: [1, 6], 2: [2, 7, 5]}}

目标是将每个子字典按键升序排序,得到:

dict2 = {1: {1: [7], 7: [6]}, 2: {2: [2, 7, 5], 3: [1, 6]}}

尝试的错误代码:

print(sorted(dict1.items(), key=lambda x: x[1][1]))

正确实现方法

利用Python 3.7+字典默认保留插入顺序的特性,结合字典推导式和sorted()函数对每个子字典单独排序:

# 修正后的原字典
dict1 = {1: {7: [6], 1: [7]}, 2: {3: [1, 6], 2: [2, 7, 5]}}

# 生成目标字典
dict2 = {outer_key: dict(sorted(inner_dict.items())) for outer_key, inner_dict in dict1.items()}

print(dict2)

运行后输出:

{1: {1: [7], 7: [6]}, 2: {2: [2, 7, 5], 3: [1, 6]}}

错误代码分析

你之前的代码存在两个核心问题:

  1. 操作对象错误:sorted(dict1.items())是对外层字典的键值对排序,而非每个子字典内部的键值对,完全偏离需求
  2. 排序逻辑错误:key=lambda x: x[1][1]试图取子字典中键为1的值作为排序依据,既不符合需求,还会在子字典无键1时触发KeyError

内容的提问来源于stack exchange,提问作者jojox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:55:24