Help needed: dynamically pull data from different levels of a dict

Chris Rebert clp2 at rebertia.com
Wed Feb 29 23:43:44 EST 2012


On Wed, Feb 29, 2012 at 7:56 PM, Peter Rubenstein
<peter.rubenstein at 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



More information about the Python-list mailing list