On Feb 17, 3:56 am, Benjamin <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list