invert dictionary with list &c

Des Small des.small at
Wed Nov 26 18:06:53 CET 2003

Lately I have found myself using a pattern to make new dictionaries
quite often, by which I mean twice:

def invert(d):
    nd = {}
    [nd.setdefault(val, []).append(key) for k, v in d]
    return nd

def count(l):
    d = {}
    [d.setdefault(w, 0) += 1 for w in l]
    return d

Is this the pythonic way to do such things?  Ideally I'd like to write
them as one liners, but I can't see how.

"[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