News for hackers. Stuff that matters.
Re:A Hodgepodge of Python by balbeit on Thursday September 15, 2011 @05:48PM (#3002257)
I always love learning little tidbits about Python like these. Thanks!

Another I found quite useful: instead of collections.defaultdict, you can use the dict's get() method to set a default value if the key doesn't exist. get() takes the key and a default value, and if the key doesn't exist it creates one with the default value provided.

  a = {}
  a['foo'] = a.get('foo',0) + 1
  # a = {'foo':1}
  a['foo'] = a.get('foo',0) + 1
  # a = {'foo':2}
It can be very useful for incrementing keys in a dict, even if they did not exist previously.
Re:A Hodgepodge of Python by randlet on Thursday September 15, 2011 @09:01PM (#3002714)
You can use the Counter class from the collections module[1] for that as well.

  >>> from collections import Counter
  >>> c = Counter()
  >>> c['foo']
  0
  >>> c['bar'] +=1
  >>> c['bar']
  1
  >>> 
[1] http://docs.python.org/dev/library/collections.html#collecti...
Re:A Hodgepodge of Python by BrandonM on Thursday September 15, 2011 @09:01PM (#3002712)
get() doesn't create a value in the dictionary, though; it only returns a default value. For what you describe, you would want setdefault(). It works here because you're assigning a value to a['foo'] after get()ing the default value.