Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69571

Re: Retrieve item deep in dict tree?

References <mailman.8818.1396461529.18130.python-list@python.org> <5d184a3a-c8d2-40d6-8055-7f7d1eb96127@googlegroups.com> <141eca25-744b-47c0-8b2b-d8d08f8b27ef@googlegroups.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-04-03 01:00 -0600
Subject Re: Retrieve item deep in dict tree?
Newsgroups comp.lang.python
Message-ID <mailman.8827.1396508455.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Apr 2, 2014 at 10:15 PM, Rustom Mody <rustompmody@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)

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Retrieve item deep in dict tree? Roy Smith <roy@panix.com> - 2014-04-02 13:58 -0400
  Re: Retrieve item deep in dict tree? John Gordon <gordon@panix.com> - 2014-04-02 18:03 +0000
  Re: Retrieve item deep in dict tree? Steven D'Aprano <steve@pearwood.info> - 2014-04-02 20:18 +0000
    Re: Retrieve item deep in dict tree? Ethan Furman <ethan@stoneleaf.us> - 2014-04-02 13:25 -0700
  Re: Retrieve item deep in dict tree? Rustom Mody <rustompmody@gmail.com> - 2014-04-02 19:41 -0700
    Re: Retrieve item deep in dict tree? Rustom Mody <rustompmody@gmail.com> - 2014-04-02 21:15 -0700
      Re: Retrieve item deep in dict tree? Steven D'Aprano <steve@pearwood.info> - 2014-04-03 05:29 +0000
      Re: Retrieve item deep in dict tree? Ian Kelly <ian.g.kelly@gmail.com> - 2014-04-03 01:00 -0600

csiph-web