I’m trying to print a dict key value dynamically.
EX:
JavaScript
x
3
1
print(data['waninfo']['1']['user']['_value']) ->"teste"
2
print(data['waninfo']['1']['pw']['_value']) -> "teste123"
3
As we see the key ‘waninfo’ and ‘1’ are fixed and i would like to use the keys after dynamically, like this:
JavaScript
1
3
1
fixedKey = "['user']['_value']"
2
print(data['waninfo']['1']+fixedKey)
3
How can i do this?
Advertisement
Answer
If there’s a constant number of keys, it might be easiest to just declare separate variables for them:
JavaScript
1
3
1
key1, key2 = 'user', '_value'
2
print(data['waninfo']['1'][key1][key2])
3
If you have a variable (or very large) number of keys, use an iterable and then iterate over it to do the nested lookups:
JavaScript
1
6
1
keys = 'user', '_value'
2
val = data['waninfo']['1']
3
for key in keys:
4
val = val[key]
5
print(val)
6