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

如何对嵌套字典的tests字段排序?实现非空与空列表位置调整

嵌套字典内容迁移与通用化处理方案

问题描述

现有如下嵌套字典:

student_dict = {
    "Student Id": {
        "Name": "student name",
        "tests": {
            "test1": ["mark", "grade", "time"],
            "test2": ["mark", "grade", "time"],
            "test3": [],
            "test4": ["mark", "grade", "time"]
        }
    }
}

需求:将tests字段中非空列表的内容,移至前面的空列表位置,原非空列表变为空。比如将test4的内容移到test3,使test3非空、test4为空。同时要求方案能适配tests新增更多键值对的场景,而非仅针对固定的test3/test4做值交换。

预期结果:

student_dict = {
    "Student Id": {
        "Name": "student name",
        "tests": {
            "test1": ["mark", "grade", "time"],
            "test2": ["mark", "grade", "time"],
            "test3": ["mark", "grade", "time"],
            "test4": []
        }
    }
}

解决方案

1. 通用化实现思路

利用Python 3.7+字典插入有序的特性,按顺序遍历tests的键:

  • 先收集所有空列表的test键(待填充的目标位置)
  • 再收集所有非空列表的test键(待迁移的源位置)
  • 按顺序将源位置的内容迁移到目标位置,迁移后源位置置为空

2. 代码实现

# 目标字典
student_dict = {
    "Student Id": {
        "Name": "student name",
        "tests": {
            "test1": ["mark", "grade", "time"],
            "test2": ["mark", "grade", "time"],
            "test3": [],
            "test4": ["mark", "grade", "time"],
            "test5": [],
            "test6": ["mark", "grade", "time"]  # 新增测试键
        }
    }
}

tests = student_dict["Student Id"]["tests"]

# 收集待填充的空test键
empty_tests = [key for key, val in tests.items() if not val]
# 收集待迁移的非空test键(排除初始已非空的项)
source_tests = [key for key, val in tests.items() if val and key not in empty_tests]

# 一一对应迁移内容
for empty_key, source_key in zip(empty_tests, source_tests):
    tests[empty_key] = tests[source_key].copy()  # 用copy避免列表引用关联
    tests[source_key] = []

# 格式化输出结果
import pprint
pprint.pprint(student_dict)

3. 执行结果

上述代码会自动处理新增的test5和test6,将test6的内容移到test5,最终tests结构为:

'tests': {'test1': ['mark', 'grade', 'time'],
          'test2': ['mark', 'grade', 'time'],
          'test3': ['mark', 'grade', 'time'],
          'test4': [],
          'test5': ['mark', 'grade', 'time'],
          'test6': []}

注意事项

  • 若空test数量多于非空待迁移test,剩余空test会保持为空;反之,剩余非空test不受影响
  • 若不需要保留原列表的独立引用,可去掉.copy()直接赋值,减少内存开销

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:35:28