Section 2 · Lesson 2

Dictionaries

Look up values by key, update records, and total values by category.

25 min 3 practice tasks
Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs by Corey Schafer on YouTube

A list is great for values in order, but often you want to look something up by name: the budget for this campaign, the full name for this country code. That’s what a dictionary (dict) does. It stores key → value pairs.

Creating a dictionary

campaign = {
    "id": 104,
    "name": "Vital Conversions Social 4",
    "channel": "social",
    "daily_budget": 400,
    "status": "active",
}

Keys (here, strings) must be unique. Values can be anything: numbers, strings, lists, even other dictionaries. One dictionary like this is a lot like one row of a table, with the keys as column names.

Reading values

campaign["channel"]          # 'social'
campaign["end_date"]         # KeyError: the key doesn't exist
campaign.get("end_date")     # None   (no error)
campaign.get("end_date", "always-on")   # 'always-on'  (your default)
"status" in campaign         # True   (checks keys)

Use square brackets when the key must exist (a typo will fail loudly, which is good), and .get() with a default when missing keys are expected.

Adding, changing and removing

campaign["status"] = "paused"                         # change a value
campaign["daily_budget"] = campaign["daily_budget"] * 1.25   # update from the current value
campaign["end_date"] = "2026-03-31"                   # new key: added automatically
del campaign["end_date"]                              # remove a key

Looping over a dictionary

Loop You get
for key in d: each key
for value in d.values(): each value
for key, value in d.items(): each key and value together
budgets = {"search": 9650, "video": 9900, "display": 8700, "social": 6200}
for channel, budget in budgets.items():
    print(f"{channel:<8} ${budget:>6,}")

The “total by category” pattern

This is one of the most useful patterns in all of data work. Start with an empty dictionary and, for each record, add to the running total for its category:

orders = [("search", 120.0), ("video", 75.5), ("search", 42.0)]

revenue_by_channel = {}
for channel, amount in orders:
    revenue_by_channel[channel] = revenue_by_channel.get(channel, 0) + amount

print(revenue_by_channel)   # {'search': 162.0, 'video': 75.5}

.get(channel, 0) is the trick: the first time a channel appears there is no total yet, so it starts from 0. Swap + amount for + 1 and the same code counts records.

Lists of dictionaries

A list of dictionaries is a simple way to hold a whole table in plain Python:

rows = [
    {"campaign": "Summit Search", "channel": "search", "spend": 682.23},
    {"campaign": "Summit Video", "channel": "video", "spend": 1210.40},
]
for row in rows:
    print(row["campaign"], row["spend"])

Tip: The “total by category” loop above is exactly what pandas’ groupby does for you in one line, across millions of rows. When you meet groupby later in the course, you’ll know what it’s doing under the hood.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Update a campaign record

One campaign is stored as a dictionary:

campaign = {
    "id": 104,
    "name": "Vital Conversions Social 4",
    "channel": "social",
    "daily_budget": 400,
    "status": "active",
}

The client approved changes. Modify campaign (don't rebuild it from scratch) so that: 1. daily_budget is 25% higher than it is now (calculate it from the current value) 2. status is "paused" 3. a new key "end_date" holds "2026-03-31"

Need a hint?
  1. Assign to a key to change it: campaign["status"] = "paused".
  2. Read the current value on the right-hand side: campaign["daily_budget"] * 1.25.
  3. Assigning to a key that doesn't exist yet adds it.
Python 3
campaign = {
    "id": 104,
    "name": "Vital Conversions Social 4",
    "channel": "social",
    "daily_budget": 400,
    "status": "active",
}

# make your changes here

print(campaign)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

Spend and campaign count by channel

Each row below is one campaign (a list of dictionaries, like rows in a spreadsheet):

rows = [
    {"campaign": "Summit Search", "channel": "search", "spend": 682.23},
    {"campaign": "Summit Video", "channel": "video", "spend": 1210.40},
    {"campaign": "Cobalt Search", "channel": "search", "spend": 455.10},
    {"campaign": "Vital Social", "channel": "social", "spend": 390.75},
    {"campaign": "Redline Video", "channel": "video", "spend": 980.00},
    {"campaign": "Urban Search", "channel": "search", "spend": 512.67},
]

Loop over rows and build two dictionaries keyed by channel:

  • spend_by_channel: total spend per channel, each rounded to 2 decimals
  • campaigns_per_channel: how many campaigns each channel has
Need a hint?
  1. d.get(key, 0) returns the current total, or 0 if the key isn't there yet.
  2. spend_by_channel[channel] = spend_by_channel.get(channel, 0) + row["spend"]
  3. Counting works the same way, but add 1 instead of the spend.
Python 3
rows = [
    {"campaign": "Summit Search", "channel": "search", "spend": 682.23},
    {"campaign": "Summit Video", "channel": "video", "spend": 1210.40},
    {"campaign": "Cobalt Search", "channel": "search", "spend": 455.10},
    {"campaign": "Vital Social", "channel": "social", "spend": 390.75},
    {"campaign": "Redline Video", "channel": "video", "spend": 980.00},
    {"campaign": "Urban Search", "channel": "search", "spend": 512.67},
]

spend_by_channel = {}
campaigns_per_channel = {}

for row in rows:
    channel = row["channel"]
    # update both dictionaries here

print(spend_by_channel)
print(campaigns_per_channel)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Look up country names

The customers table stores two-letter country codes. Reports need full names:

country_names = {"US": "United States", "CA": "Canada", "UK": "United Kingdom", "DE": "Germany"}
codes = ["US", "IN", "DE", "CA", "FR"]

Build a list full_names with the full name for each code in codes, in the same order. Codes that aren't in the dictionary should become "Other". (Expected: ["United States", "Other", "Germany", "Canada", "Other"].)

Need a hint?
  1. country_names["IN"] would raise a KeyError because "IN" is not a key.
  2. country_names.get(code, "Other") returns the name, or "Other" when the code is missing.
Python 3
country_names = {"US": "United States", "CA": "Canada", "UK": "United Kingdom", "DE": "Germany"}
codes = ["US", "IN", "DE", "CA", "FR"]

full_names = []
for code in codes:
    full_names.append(code)  # change this line

print(full_names)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country