Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a single variable to index into nested dictionaries

Imagine you have a dictionary in python: myDic = {'a':1, 'b':{'c':2, 'd':3}}. You can certainly set a variable to a key value and use it later, such as:

myKey = 'b'
myDic[myKey]
>>> {'c':2, 'd':3}

However, is there a way to somehow set a variable to a value that, when used as a key, will dig into sub dictionaries as well? Is there a way to accomplish the following pseudo-code in python?

myKey = "['b']['c']"
myDic[myKey]
>>> 2

So first it uses 'b' as a key, and whatever is reurned it then uses 'c' as a key on that. Obviously, it would return an error if the value returned from the first lookup is not a dictionary.

like image 949
J-bob Avatar asked Dec 26 '22 13:12

J-bob


2 Answers

No, there is nothing you can put into a variable so that myDict[myKey] will dig into the nested dictionaries.

Here is a function that may work for you as an alternative:

def recursive_get(d, keys):
    if len(keys) == 1:
        return d[keys[0]]
    return recursive_get(d[keys[0]], keys[1:])

Example:

>>> myDic = {'a':1, 'b':{'c':2, 'd':3}}
>>> recursive_get(myDic, ['b', 'c'])
2
like image 86
Andrew Clark Avatar answered Feb 16 '23 22:02

Andrew Clark


No, not with a regular dict. With myDict[key] you can only access values that are actually values of myDict. But if myDict contains other dicts, the values of those nested dicts are not values of myDict.

Depending on what you're doing with the data structure, it may be possible to get what you want by using tuple keys instead of nested dicts. Instead of having myDic = {'b':{'c':2, 'd':3}}, you could have myDic = {('b', 'c'):2, ('b', 'd'): 3}. Then you can access the values with something like myDic['b', 'c']. And you can indeed do:

val = 'b', 'c'
myDic[val]
like image 21
BrenBarn Avatar answered Feb 16 '23 21:02

BrenBarn