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

如何同时获取列表嵌套字典中指定key的值及对应的列表索引

解决方案

你可以结合Python内置的enumerate()函数遍历列表,同时获取索引和对应的字典元素,匹配到目标键后直接取值即可:

方法1:确定目标键一定存在的场景

data = [
    {
        'name1': 'aaa',
    },
    {
        'name2': 'bbb',
    },
    {
        'name3': 'ccc',
    },
    {
        'name4': 'ddd',
    }
]

target_key = 'name1'
for index, item in enumerate(data):
    if target_key in item:
        target_index = index
        target_value = item[target_key]
        break

print(f"索引:{target_index},值:{target_value}")

运行输出为:索引:0,值:aaa

方法2:兼容目标键不存在的场景

如果不能确定目标键一定存在,可以加兜底判断避免报错:

target_key = 'name1'
result = None
for index, item in enumerate(data):
    if target_key in item:
        result = (index, item[target_key])
        break

if result:
    target_index, target_value = result
    print(f"索引:{target_index},值:{target_value}")
else:
    print(f"未找到键为{target_key}的元素")
  • 原理说明:enumerate()函数会在遍历可迭代对象时,同时返回元素的索引位置和元素本身,遍历过程中检查当前字典是否包含目标键,匹配到就可以同时拿到索引和对应值,匹配到后直接中断循环,不需要遍历整个列表,执行效率较高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:45:04