Python Collections

Two very interesting use cases of python collections are :

  • defaultdict
  • Counter

defaultdict Examples:

[1]

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:
cities_by_state[state].append(city)

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

Output:

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

 

Counter Examples:

[1]

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

Output:

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

 

 

 

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s