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

Python中如何用字符串变量作为嵌套列表/字典的索引?

嵌套数据的字符串路径取值解决方案

场景说明

给定嵌套的字典/列表数据data,以及字符串形式的访问路径foo(比如"['virtualInterfaces'][2]['interfaceState']"),需要从data中取出对应位置的值,解决直接使用eval时的错误或安全风险问题。

方法一:正确使用eval(简单但需注意安全)

之前的错误在于直接拼接变量data和字符串foo,正确的做法是把data作为变量名嵌入表达式:

data = {'virtualInterfaces': [{"interfaceName": "abc", "interfaceState": "online"}, {"interfaceName": "axc", "interfaceState": "online"}, {"interfaceName": "xpto", "interfaceState": "offline"}]}
foo = "['virtualInterfaces'][2]['interfaceState']"

value = eval(f"data{foo}")
print(value)  # 输出 'offline'

注意:如果foo来自不可信的外部输入,绝对不要用这个方法,因为eval会执行任意代码,存在严重安全隐患。

方法二:解析路径手动遍历(安全通用)

如果要避免安全风险,或者需要处理任意层数的嵌套结构,可以手动解析路径字符串,逐层访问数据:

data = {'virtualInterfaces': [{"interfaceName": "abc", "interfaceState": "online"}, {"interfaceName": "axc", "interfaceState": "online"}, {"interfaceName": "xpto", "interfaceState": "offline"}]}
foo = "['virtualInterfaces'][2]['interfaceState']"

def get_nested_value(data, path_str):
    # 清理路径字符串,拆分出每个访问节点
    path_nodes = path_str.replace('[', '').replace(']', '').split(',')
    current_data = data
    for node in path_nodes:
        node = node.strip()
        # 判断是字典键(带引号)还是列表索引(数字)
        if node.startswith("'") and node.endswith("'"):
            key = node[1:-1]
            current_data = current_data[key]
        else:
            index = int(node)
            current_data = current_data[index]
    return current_data

value = get_nested_value(data, foo)
print(value)  # 输出 'offline'

这个方法支持任意层数的嵌套字典和列表,完全规避了eval的安全问题,适合绝大多数场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:25