Retrieve item deep in dict tree?

Rustom Mody rustompmody at gmail.com
Wed Apr 2 22:41:33 EDT 2014


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!!'
>>>

I used a nested thus
>>> nested = {'a':{'b':{'c':"Hiii!!"}}}

But what you are REALLY looking for is what Steven/Gordon gave <wink>

In order to see more visibly that those whiles are just reduces
you may want to rewrite as:

>>> reduce((lambda tr, att: str(tr) + "[" + str(att) + "]"), ['a','b','c'], "nested")
'nested[a][b][c]'

IOW the 'theorem' I am using is that

reduce(op, id, l)

is short for

while l: 
  id, l = op(id, l[0]), l[1:]
return id



More information about the Python-list mailing list