Home > Net >  Nested Dictionary (JSON): Merge multiple keys stored in a list to access its value from the dict
Nested Dictionary (JSON): Merge multiple keys stored in a list to access its value from the dict

Time:12-02

I have a JSON with an unknown number of keys & values, I need to store the user's selection in a list & then access the selected key's value; (it'll be guaranteed that the keys in the list are always stored in the correct sequence).

Example

I need to access the value_key1-2.

mydict = {
    'key1': {
        'key1-1': {
            'key1-2': 'value_key1-2'
        },
    },
    'key2': 'value_key2'
}

I can see the keys & they're limited so I can manually use:

>>> print(mydict['key1']['key1-1']['key1-2'])
>>> 'value_key1-2'

Now after storing the user's selections in a list, we have the following list:

Uselection = ['key1', 'key1-1', 'key1-2']

How can I convert those list elements into the similar code we used earlier?
How can I automate it using Python?

CodePudding user response:

You have to loop the list of keys and update the "current value" on each step.

val = mydict

try:
    for key in Uselection:
        val = val[key]
except KeyError:
    handle non-existing keys here

Another, more 'posh' way to do the same (not generally recommended):

from functools import reduce

val = reduce(dict.get, Uselection, mydict)
  • Related