Python使用字符串变量作为嵌套列表/字典的索引/键

xt0899hw  于 2023-03-24  发布在  Python
关注(0)|答案(1)|浏览(122)
data = {'virtualInterfaces': [{"interfaceName": "abc", "interfaceState": "online"}, {"interfaceName": "axc", "interfaceState": "online"}, {"interfaceName": "xpto", "interfaceState": "offline"}]}

foo = "['virtualInterfaces'][2]['interfaceState']"

我需要使用var“foo”从data获取一个特定的值
例如

data[foo] #should return "offline"

我试着用eval
value = eval(data + foo)
Foo可以有任意数量的嵌套list/dict

yqkkidmi

yqkkidmi1#

foo包含文字索引字符串,而data不是字符串,而是字典对象。所以你必须把data放在引号中才能使用eval

value = eval('data' + foo)

相关问题