Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Access hierarchical dict element from list of keys

Let's say I have a regular "dict-of-dicts" as follows:

d = {}
d['a'] = {}
d['a']['b'] = 3

I can of course access the element using d['a']['b'].

In my case, I have a recursive application, in which I keep the current state as a list of keys. So I would have

my_key = ['a', 'b']

How do I access the value 3, using my_key? The issue, of course, is that my_key can be arbitrarily long (deep).

I realize I can write another traversal function or so, but it seems like there should be a straightforward way of doing so. Any ideas?

like image 274
user1496984 Avatar asked Dec 25 '22 11:12

user1496984


1 Answers

You could use reduce to iteratively index each layer of dict with a different key:

>>> from functools import reduce #only necessary in 3.X
>>> d = {}
>>> d['a'] = {} #I'm assuming this is what you meant to type
>>> d['a']['b'] = 3
>>> keys = ("a", "b")
>>> reduce(dict.get, keys, d)
3
like image 55
Kevin Avatar answered Dec 28 '22 14:12

Kevin