Python Collections

Two very interesting use cases of python collections are :

  • defaultdict
  • Counter

defaultdict Examples:


from collections import defaultdict

city_list = [(‘TX’,’Austin’), (‘TX’,’Houston’), (‘NY’,’Albany’), (‘NY’, ‘Syracuse’), (‘NY’, ‘Buffalo’), (‘NY’, ‘Rochester’), (‘TX’, ‘Dallas’), (‘CA’,’Sacramento’), (‘CA’, ‘Palo Alto’), (‘GA’, ‘Atlanta’)]

cities_by_state = defaultdict(list)

for state, city in city_list:

for state, cities in cities_by_state.iteritems():
print state, ‘, ‘.join(cities)


NY Albany, Syracuse, Buffalo, Rochester
CA Sacramento, Palo Alto
GA Atlanta
TX Austin, Houston, Dallas


Counter Examples:


myCounter = Counter([‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘b’])
print myCounter

# print the 2 most common words and their counts
for word, count in myCounter.most_common(2):
print word, count


Counter({‘b’: 3, ‘a’: 2, ‘c’: 1})
b 3
a 2





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s