invert dictionary with list &c

Mel Wilson mwilson at
Wed Nov 26 20:17:32 CET 2003

In article <yyrjbrqz3ql5.fsf at>,
Des Small <des.small at> wrote:
>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.

   Once you've written the above, they are one-liners:

    inverted_dict = invert (some_dict)

Why would you need less?  There's little doubt in any
reader's mind that inverting a dictionary is really what
you're doing; there's little chance of a typo sneaking in
and messing up the process without anybody noticing, etc.

        Regards.        Mel.

More information about the Python-list mailing list