Retrieve item deep in dict tree?

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 3 03:00:10 EDT 2014


On Wed, Apr 2, 2014 at 10:15 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> 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!!'

That breaks if the dicts are ever replaced with an alternate mapping
implementation (or a dict subclass that overrides the get method), and
incorrectly returns None instead of raising KeyError if the last key
in the sequence does not exist (and if any of the other keys don't
exist, you'll get a TypeError instead of a KeyError). This is more
robust:

import operator
reduce(operator.getitem, ['a', 'b', 'c'], nested)



More information about the Python-list mailing list