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