Retrieve item deep in dict tree?

Steven D'Aprano steve at pearwood.info
Wed Apr 2 16:18:45 EDT 2014


On 2014年4月02日 13:58:16 -0400, Roy Smith wrote:
> I have a big hairy data structure which is a tree of nested dicts. I
> have a sequence of strings which represents a path through the tree. 
> Different leaves in the tree will be at different depths (which range
> from 1 to about 4 or 5 at most). I want to get the value stored at that
> path. Thus, if
>> keys = ['foo', 'bar', 'baz']
>> I want to retrieve tree['foo']['bar']['baz'].
>> Is there some idiomatic, non-cryptic way to write that as a one-liner?

Er, idiomatic one liner? No, not really. But a helper function makes 
nearly anything into a one-liner:
def traverse(tree, *keys):
 t = tree
 for k in keys:
 t = t[k]
 return t
# one-liner
leaf = traverse(tree, *list_of_keys)
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /