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


Groups > comp.lang.python > #69550

Re: Retrieve item deep in dict tree?

From John Gordon <gordon@panix.com>
Newsgroups comp.lang.python
Subject Re: Retrieve item deep in dict tree?
Date 2014-04-02 18:03 +0000
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <lhhjcr$e5s$1@reader1.panix.com> (permalink)
References <mailman.8818.1396461529.18130.python-list@python.org>

Show all headers | View raw


In <mailman.8818.1396461529.18130.python-list@python.org> Roy Smith <roy@panix.com> writes:

> 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 =3D ['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.

How about three lines?

    subtree = tree
    for key in keys:
        subtree = subtree.get(key)

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon@panix.com    watch 'House', or a real serial killer to watch 'Dexter'.

Back to comp.lang.python | Previous | NextPrevious in thread | Next 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