flattening a dict

Boris Borcic bborcic at gmail.com
Mon Feb 18 11:49:59 EST 2008


Duncan Booth wrote:
> Boris Borcic <bborcic at gmail.com> wrote:
> 
>> It is more elementary in the mathematician's sense, and therefore
>> preferable all other things being equal, imo. I've tried to split
>> 'gen' but I can't say the result is so much better.
>>
>> def flattendict(d) :
>>        gen = lambda L : (x for M in exp(L) for x in rec(M))
>>        exp = lambda L : (L+list(kv) for kv in L.pop().iteritems())
>>        rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M]
>>        return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))
> 
> Why, why, why, why are you using lambda here?

Because the 3 lambdas make manifest that they could be combined into a single 
expression and thus reveal that they replace a single expression.

> It only makes the code harder 
> to read

Matter of perceptions. I myself tend to find

def g(...) :
    def f(x) :
        return (whatever)
    return y(f)

a bit hard to follow. So frankly I don't feel it betters anything to write

def flattendict(d) :
           def gen(L) :
               return (x for M in exp(L) for x in rec(M))

           def exp(L) :
               return (L+list(kv) for kv in L.pop().iteritems())

           def rec(M) :
               return gen(M) if isinstance(M[-1],dict) else [M]

           return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))

But whatever to please you

Cheers, BB





More information about the Python-list mailing list