invert dictionary with list &c

Des Small des.small at bristol.ac.uk
Thu Nov 27 12:15:49 CET 2003


John Hunter <jdhunter at ace.bsd.uchicago.edu> writes:

> >>>>> "Des" == Des Small <des.small at bristol.ac.uk> writes:
> 
>   def count(l):
>       d = {}
>       [d.setdefault(w, 0) += 1 for w in l]
>       return d
> 
> This code raises a SyntaxError.  

So it does.  Whatever it was I had working yesterday wasn't that,
then.

> The standard idiom for counting all the elements in a list with a
> dictionary is
> 
>   def count(l):
>       d = {}
>       for w in l: d[w] = d.get(w,0) + 1
>       return d
> 
> I think the basic rule of thumb is to use the setdefault approach for
> mutable objects (list, dict) and the get approach for immutable
> elements (strings, ints, floats, tuples).

What I really want is a generic pattern that constructs dictionary
from iterators in a clean way, while allowing mutation of the
dictionary entry as necessary.

> Also, many here would find using list comprehensions while ignoring
> their return value, as you did in '[d.setdefault(w, 0) += 1 for w in
> l]' to be an abuse of list comps.  At least I've been admonished for
> doing so, and so I must now admonish you to continue the cycle of
> violence.

I shall be breaking the cycle by not caring, although if and when
generator comprehensions allow me to comply with your preferences I'll
probably do so.  

[...]

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