Skip to main content

Command Palette

Search for a command to run...

Default Dict

Updated
•1 min read•View as Markdown
Default Dict

collections.defaultdict is a nifty little fella. It takes a callable with no arguments in order to determine what to initialize a nonexistent key with. One neat trick is to use it for adding up field totals:

from collections import defaultdict

# Assume this was input from tabular data
q_rev = [
    ("Books", 2250.10),
    ("Toys", 123.34),
    ("Tools", 988.34),
    ("Books", 1259.42),
    ("Toys", 322.24),
    ("Tools", 787.34),
    ("Books", 2189.88),
    ("Toys", 533.24),
    ("Tools", 789.31),
    ("Books", 1103.24),
    ("Toys", 319.34),
    ("Tools", 1001.21),
]

totals = defaultdict(float)

for product, total in q_rev:
    totals[product] += total

for product, total in totals.items():
    print(f"{product}: {total:,.2f}")

# output looks like
# Books: $6,802.64
# Toys: $1,298.16
# Tools: $3,566.20