Skip to content

Instantly share code, notes, and snippets.

@adambard
Created February 23, 2011 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adambard/839705 to your computer and use it in GitHub Desktop.
Save adambard/839705 to your computer and use it in GitHub Desktop.
"""
A simpler pivot table for non-python people.
Pythonisms present:
1. You can iterate over a list of tuples using `for ... in` and map each tuple to a variable.
2. Dicts exist and are great.
3. Iterating over a dict returns the key.
4. Attempting to access a variable that doesn't exist in a dict raises a KeyError.
While these are all language-specific things, I argue that all
can be inferred from reading the code. There are a million ways to write any given routine.
"""
# Sales is a list of tuples
sales = [('Scotland', 'Edinburgh', 20000),
('Scotland', 'Glasgow', 12500),
('Wales', 'Cardiff', 29700),
('Wales', 'Bangor', 12800),
('England', 'London', 90000),
('England', 'Manchester', 45600),
('England', 'Liverpool', 29700)]
# Use a dict to store output
out_sales = {}
# Populate output dict
for region, city, total in sales:
# Set-or-increment that key
try:
out_sales[region] += total
except KeyError:
out_sales[region] = total
# Print the summary
for region in out_sales:
print "%s: %d" % (region, out_sales[region])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment