invert dictionary with list &c

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Nov 26 20:46:50 EST 2003


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

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).

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.

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

I think that striving for one-liners is not pythonic.  Most python
coders value readability over compactness.  It's more important to
write an appropriately named function that works and is readable and
efficient than it is to write a one liner.

John Hunter





More information about the Python-list mailing list