flattening a dict

Arnaud Delobelle arnodel at googlemail.com
Sun Feb 17 03:05:06 EST 2008


On Feb 17, 3:56 am, Benjamin <musiccomposit... at gmail.com> wrote:
> How would I go about "flattening" a dict with many nested dicts
> within? The dicts might look like this:
> {"mays" : {"eggs" : "spam"},
> "jam" : {"soda" : {"love" : "dump"}},
> "lamba" : 23}
>
> I'd like it to put "/" inbetween the dicts to make it a one
> dimensional dict and look like this:
> {"mays/eggs" : "spam",
> "jam/soda/love" : "dump",
> "lamba" : 23
>
> }

In Python you can do anything, even flatten a dictionary:

from itertools import chain

def flattendict(d, pfx='', sep='/'):
    if isinstance(d, dict):
        if pfx: pfx += sep
        return chain(*(flattendict(v, pfx+k, sep) for k, v in
d.iteritems()))
    else:
        return (pfx, d),

test = {"mays" : {"eggs" : "spam"},
        "jam" : {"soda" : {"love" : "dump"}},
        "lamba" : 23
        }

>>> print dict(flattendict(test))
{'lamba': 23, 'mays/eggs': 'spam', 'jam/soda/love': 'dump'}

You an even have other separators ;)

>>> print dict(flattendict(test, sep='.'))
{'lamba': 23, 'jam.soda.love': 'dump', 'mays.eggs': 'spam'}

--
Arnaud




More information about the Python-list mailing list