Dictionaries

Topic 3 of 5 in Collections5 min readBeginnerFree course

Overview

Lists find things by position. But often you want to find things by name: the price of “tea”, the phone number for “Asha”, the capital of “France”. A dictionary (dict) stores key → value pairs and finds any value by its key instantly, however big the dictionary gets.

Creating a dictionary

Python
prices = {"tea": 3.5, "coffee": 4.0, "cake": 5.25}
ages = {"Asha": 29, "Ben": 34}
empty = {}

A dictionary maps keys to values. prices = {“tea”: 3.5, “coffee”: 4.0, “cake”: 5.25}: the unique keys “tea”, “coffee” and “cake” map to the values 3.5, 4.0 and 5.25. prices[“tea”] gives 3.5; prices.get(“pie”, 0) gives 0 with no KeyError; prices[“pie”] = 4.75 adds an entry; and for item, price in prices.items() loops over the pairs.

Each entry is key: value, separated by commas, inside curly braces.

  • Keys are unique. Assigning to an existing key replaces its value.
  • Keys must be immutable: strings, numbers or tuples. Lists can’t be keys.
  • Values can be anything: numbers, strings, lists, other dictionaries.
  • Dictionaries remember insertion order: loops go through keys in the order they were added.

Reading values

Python
prices["tea"]                 # 3.5
prices["pie"]                 # KeyError: 'pie'
prices.get("pie")             # None — no error
prices.get("pie", 0)          # 0 — your default
"tea" in prices               # True — checks KEYS, not values
len(prices)                   # 3

Use d[key] when the key must exist (a missing key is a bug you want to hear about); use d.get(key, default) when missing is normal.

Adding, changing and removing

Python
prices["pie"] = 4.75          # add a new key
prices["tea"] = 3.75          # change an existing one
prices["tea"] += 0.25         # update based on the old value

del prices["cake"]            # remove (KeyError if absent)
price = prices.pop("pie")     # remove AND return the value
prices.pop("muffin", None)    # no error if absent

prices.update({"tea": 4.0, "scone": 3.0})   # add/overwrite several
prices |= {"juice": 2.5}                    # the same, with an operator

Looping over a dictionary

Python
for item in prices:                     # keys
    print(item)

for price in prices.values():           # values
    print(price)

for item, price in prices.items():      # both — the most common
    print(f"{item}: {price:.2f}")

items() gives (key, value) tuples, which the loop unpacks. To loop in sorted order, wrap it: for item, price in sorted(prices.items()): sorts by key.

As with lists, don’t add or remove keys while looping over the dictionary itself (Python raises RuntimeError: dictionary changed size during iteration). Loop over list(d) instead if you must.

Counting with a dictionary

One of the most useful patterns in programming — count how many times each thing appears:

Python
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

get(word, 0) returns the current count, or 0 the first time a word is seen. (The standard library’s collections.Counter does this in one line — see The standard library.)

To find the key with the largest value: max(counts, key=counts.get).

Grouping with a dictionary of lists

Python
groups = {}
for name, team in [("Asha", "red"), ("Ben", "blue"), ("Chen", "red")]:
    groups.setdefault(team, []).append(name)
# {'red': ['Asha', 'Chen'], 'blue': ['Ben']}

setdefault(key, default) returns the existing value, or inserts the default first if the key is missing.

Nested data

Dictionaries and lists combine to describe almost any data — this is exactly the shape of JSON from web APIs (CSV and JSON):

Python
user = {
    "name": "Asha",
    "languages": ["Python", "SQL"],
    "address": {"city": "Pune", "country": "IN"},
}
user["languages"][0]          # 'Python'
user["address"]["city"]       # 'Pune'

Building dictionaries

Python
dict(tea=3.5, coffee=4.0)                     # keyword style
dict(zip(["a", "b"], [1, 2]))                 # {'a': 1, 'b': 2}
{name: len(name) for name in ["Asha", "Ben"]} # dict comprehension (next lessons)

When to use a dictionary: whenever you think “look up X by Y” — prices by item, users by ID, counts by word.

Exercise

Word counter and inventory

(1) Count how often each word appears in the sentence in the starter (ignore case and the full stop) using a dictionary and .get(), then print the counts for the and cat, and the most common word with its count. (2) For the inventory: add "pears": 8, reduce apples by 2, remove bananas with .pop() and print how many were removed, then print each item as apples: 10 in alphabetical order of the item names.

Python
sentence = "The cat sat on the mat and the dog sat on the cat."

# 1. Word counts
counts = {}

inventory = {"apples": 12, "bananas": 5, "cherries": 30}

# 2. Update and print the inventory

Summary

  • A dictionary maps unique keys to values: {"tea": 3.5}; look up with d[key].
  • d[key] = value adds or updates; del d[key] or d.pop(key) removes.
  • d[key] raises KeyError if the key is missing; d.get(key, default) returns a default instead.
  • Loop with for key, value in d.items():; dictionaries keep insertion order.
  • Keys must be immutable (strings, numbers, tuples); values can be anything, including lists and other dicts.