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

Python嵌套字典中按主字典长度为'place'字段添加编号需求

给嵌套字典的子字典添加名次编号

首先看你的原始字典:

{
    'SVF': {'place': '', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'},
    'VBM': {'place': '', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434'},
    'SVM': {'place': '', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'}
}

要给每个子字典的place字段添上编号,核心思路是先按赛车成绩(时间越短名次越高)排序,再依次分配编号。以下是具体实现代码:

# 原始数据
race_data = {
    'SVF': {'place': '', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'},
    'VBM': {'place': '', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434'},
    'SVM': {'place': '', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'}
}

# 把时间字符串转成秒数,方便排序比较
def convert_time(time_str):
    mins, secs = time_str.split(':')
    return int(mins)*60 + float(secs)

# 按时间从短到长排序,对应名次从高到低
sorted_data = sorted(race_data.items(), key=lambda item: convert_time(item[1]['time']))

# 给每个条目分配名次编号
for rank, (driver_key, details) in enumerate(sorted_data, start=1):
    details['place'] = str(rank)

# 转成字典(Python3.7+会保留排序后的顺序)
final_result = dict(sorted_data)

print(final_result)

执行后得到的结果:

{
    'SVF': {'place': '1', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'},
    'VBM': {'place': '2', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434'},
    'SVM': {'place': '3', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'}
}

如果不需要按成绩排序,只想按原始字典的顺序直接编号,用下面的简化代码就行:

for rank, (driver_key, details) in enumerate(race_data.items(), start=1):
    details['place'] = str(rank)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:20:54