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

Python从字典提取多值时如何检查指定索引是否存在并赋值打印

Python索引存在性检查及赋值方案

两种常见场景的判断逻辑如下:

  • 若x[0]为列表/元组这类有序序列:通过判断索引是否小于序列总长度,确认索引是否合法
  • 若x[0]为字典:直接判断数字键是否存在于字典的键集合中

批量处理实现

适合需要一次性检查多个索引的场景,代码更简洁:

import json

# 原有JSON解析逻辑
x = json.loads(y)
target = x[0]
# 要检查的索引列表
check_ids = [4, 5, 6]

# 遍历检查+处理
val_map = {}
for idx in check_ids:
    # 处理序列类型
    if isinstance(target, (list, tuple)):
        if idx < len(target):
            current_val = target[idx]
            print(f"索引{idx}值为:{current_val}")
            val_map[f"z{idx+1}"] = current_val
    # 处理字典类型
    elif isinstance(target, dict):
        if idx in target:
            current_val = target[idx]
            print(f"键{idx}值为:{current_val}")
            val_map[f"z{idx+1}"] = current_val

# 按原有命名规则取变量,不存在则返回None
z5 = val_map.get("z5")
z6 = val_map.get("z6")
z7 = val_map.get("z7")

单索引判断实现

适合只需要单独检查某一个索引的场景:

target = x[0]
# 单独检查索引4的示例
z5 = None
if isinstance(target, (list, tuple)) and 4 < len(target):
    z5 = target[4]
    print(z5)
elif isinstance(target, dict) and 4 in target:
    z5 = target[4]
    print(z5)

内容的提问来源于stack exchange,提问作者Dakota Mac Dylan Carter MacBai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 10:15:02