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

Python如何用列表推导式为字典列表的每个元素添加索引字段

你可以结合enumerate()函数和列表推导式实现,有两种常用写法适配不同Python版本,两种写法都不会修改原列表中的字典,更加安全:

Python 3.9+ 版本(支持字典合并运算符|)

result = [{"index": idx} | item for idx, item in enumerate(l)]

兼容所有Python3版本(用字典解包实现)

result = [{**item, "index": idx} for idx, item in enumerate(l)]

如果确实需要直接修改原列表中的字典,可以用下面的写法(不推荐,会改动原数据):

result = [item.update({"index": idx}) or item for idx, item in enumerate(l)]

这里利用了dict.update()返回None的特性,用or item返回更新后的字典对象。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:18:03