Retrieve item deep in dict tree?

Rustom Mody rustompmody at gmail.com
Thu Apr 3 00:15:23 EDT 2014


On Thursday, April 3, 2014 8:11:33 AM UTC+5:30, Rustom Mody wrote:
> On Wednesday, April 2, 2014 11:28:16 PM UTC+5:30, 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?

> > I'm using Python 2.7.

> What you are asking for is probably:

>  >>> reduce((lambda tr, att: tr[att]), ['a','b','c'], nested)
> 'Hiii!!'

Shorter version:

>>>    reduce(dict.get, ['a','b','c'], nested)
'Hiii!!'



More information about the Python-list mailing list