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