In article <yyrjbrqz3ql5.fsf at pc156.maths.bris.ac.uk>,
Des Small <des.small at bristol.ac.uk> 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.