invert dictionary with list &c
Des Small
des.small at bristol.ac.uk
Thu Nov 27 09:30:40 EST 2003
Des Small <des.small at bristol.ac.uk> writes:
> anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> writes:
[...]
> This, however, has given me ideas. It was never concision I wanted
> but rather redundancy elimination, and the pattern I wanted _can_ be
> written:
>
> def dict_cons(iter, func, default):
> def process_element(d, (k, v)):
> val = d.get(k, default)
> d.update(dict([[k, func(v, val)]]))
> return d
> return reduce(process_element, iter, {})
Or rather:
def dict_cons(iter, func, default):
def process_element(d, (k, v)):
d[k] = func(v, d.get(k, default))
return d
return reduce(process_element, iter, {})
def count(l):
def pair_pad(l): return [(e, ()) for e in l]
return dict_cons(pair_pad(l), lambda k,d: d+1, 0)
def invert(d):
def invertitems(l):
for k,v in l: yield v,k
def addtolist(k, l): return l+[k]
return dict_cons(invertitems(d.iteritems()),
addtolist, [])
> Which is not to say that it should be, of course.
> Whereupon, we can say:
>
> def count(l):
> def pair_pad(l): return [(e, ()) for e in l]
> return dict_cons(pair_pad(l), lambda k,d: d+1, 0)
>
> def invert(d):
> def invertitems(l): for k,v in l: yield v,k
> def addtolist(k, l): return l+[k]
> return dict_cons(invertitems(d.iteritems()),
> addtolist, [])
>
> Perhaps I'm terminally unpythonic, but I quite like these.
[...]
--
"[T]he structural trend in linguistics which took root with the
International Congresses of the twenties and early thirties [...] had
close and effective connections with phenomenology in its Husserlian
and Hegelian versions." -- Roman Jakobson
More information about the Python-list
mailing list