-2

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?

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • Does this answer your question? [Dynamically accessing nested dictionary keys?](https://stackoverflow.com/questions/39818669/dynamically-accessing-nested-dictionary-keys) – Pranav Hosangadi Jul 05 '22 at 15:34

1 Answers1

0

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)
Samwise
  • 68,105
  • 3
  • 30
  • 44