Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #21065
| References | <BLU150-W94B1B3F5A35DDFE877D1A9C6C0@phx.gbl> |
|---|---|
| Date | 2012-02-29 20:43 -0800 |
| Subject | Re: Help needed: dynamically pull data from different levels of a dict |
| From | Chris Rebert <clp2@rebertia.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.311.1330577028.3037.python-list@python.org> (permalink) |
On Wed, Feb 29, 2012 at 7:56 PM, Peter Rubenstein
<peter.rubenstein@hotmail.com> wrote:
> Hi,
>
> I'd appreciate a bit of help on this problem. I have some data that I've
> converted to a dict and I want to pull out individual pieces of it.
>
> Simplified version--
>
> a={'1':'a', '2':'b', '3':{4:'d'}, '5':{'6': {'7': [ {'8':'e'}, {'9':'f'} ] }
> } }
>
> I'd like to be able to code something like:
>
> data_needed = ['1', '2', '3:4', '5:6:7-8']
> for val in data_needed:
> answer=extract_from(a,val)
> print answer
>
> And get:
> a
> b
> c
"c" apparently sprung completely out of thin air...
> d
> e
>
> Problem is I can't figure out what extract_from would look like, such that
> it would proceed dynamically down to the right level. I'm open to the
> possibility that I'm not approaching this the right way.
data_needed = ['1', '2', ('3', '4'), ('5', '6', '7', 0, '8')]
def extract_from(mapping, key_path):
current = mapping
for key in key_path:
current = current[key]
return current
I would perhaps try and restructure the data into something less
generic than nested dicts & lists, e.g. objects. You then might be
able to introduce helper querying methods.
I would also be worried about Law of Demeter violations, but
fortunately your concrete example doesn't reach any deeper than 2
levels.
Cheers,
Chris
--
http://chrisrebert.com
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Help needed: dynamically pull data from different levels of a dict Chris Rebert <clp2@rebertia.com> - 2012-02-29 20:43 -0800
csiph-web