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

Question:

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?

Asked By: Ali Abdi

||

Answers:

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)
Answered By: gog
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.