简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM