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

如何在Python的字典列表中添加索引作为键值对

为字典列表添加索引字段的解决方案

问题描述

现有如下格式的字典列表:

[
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'}
]

需要为每条记录新增index键,对应其在列表中的索引值(从0开始),最终输出如下:

[
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index':0},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index':1},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index':2}
]

解决方案

下面提供两种常用的Python实现方式:

1. 直接修改原列表

使用enumerate()遍历列表,同时获取索引和字典元素,直接在原字典上添加index字段:

data = [
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'}
]

for idx, item in enumerate(data):
    item['index'] = idx

print(data)

2. 生成新列表(不修改原数据)

如果不想改动原始列表,可以通过列表推导式创建一个包含索引的新列表:

data = [
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'},
    {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z'}
]

new_data = [{**item, 'index': idx} for idx, item in enumerate(data)]

print(new_data)

这里使用字典解包**item复制原字典的所有键值对,再添加index字段,避免修改原数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:05:25