Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python use string variable as index/key for nested list/dict

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

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

I need to use the var "foo" to get a specific value from data

e.g

data[foo] #should return "offline"

I tried to use eval

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

value = eval(data + foo)

But didn´t work.
Foo can have any number of nested list/dict

>Solution :

foo contains the literal indexing string, whereas data is not a string, but the dictionary object. So you have to put data in quotes to use eval:

value = eval('data' + foo)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading