← Back to Tutorials Chapter 8

Dictionaries

Dictionary Basics

A dictionary stores key-value pairs, enclosed in curly braces {}:

student = {"name": "Alice", "age": 25, "grade": "A"}
empty = {}
pairs = dict([("a", 1), ("b", 2)])
kwargs = dict(name="Bob", age=30)

Accessing Values

d = {"name": "Alice", "age": 25}

d["name"]      # "Alice"
d.get("name")  # "Alice"
d.get("job")        # None (no error)
d.get("job", "N/A") # "N/A" (default)
# d["job"]     # KeyError!

Adding and Updating

d = {"a": 1}
d["b"] = 2       # add new key
d["a"] = 99      # update existing
d.update({"c": 3, "d": 4})  # merge
d.update(e=5, f=6)  # keyword form

Removing Items

d = {"a": 1, "b": 2, "c": 3, "d": 4}

d.pop("a")        # removes 'a' and returns 1
d.pop("x", None)  # returns None (safe)
d.popitem()       # removes & returns (key, value) pair
del d["b"]        # removes key
d.clear()         # empties dict

View Objects

d = {"name": "Alice", "age": 25, "grade": "A"}

d.keys()    # dict_keys(['name', 'age', 'grade'])
d.values()  # dict_values(['Alice', 25, 'A'])
d.items()   # dict_items([('name', 'Alice'), ('age', 25), ('grade', 'A')])

Looping Over Dictionaries

d = {"a": 1, "b": 2, "c": 3}

for key in d:
    print(key, d[key])

for key, value in d.items():
    print(key, value)

for value in d.values():
    print(value)

Checking Membership

d = {"name": "Alice", "age": 25}

"name" in d       # True (checks keys)
"Alice" in d      # False (not in keys)
"Alice" in d.values()  # True
len(d)            # 2

Nested Dictionaries

users = {
    "alice": {"age": 25, "city": "NYC", "active": True},
    "bob": {"age": 30, "city": "LA", "active": False},
    "eve": {"age": 22, "city": "Chicago", "active": True},
}

print(users["alice"]["city"])  # NYC

# List active users
active = [name for name, info in users.items() if info["active"]]
print(active)  # ['alice', 'eve']

Dictionary Comprehension

squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 4}

even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

# Swap keys and values
original = {"a": 1, "b": 2}
reversed = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b'}

defaultdict

collections.defaultdict returns a default value for missing keys:

from collections import defaultdict

# Group words by first letter
words = ["apple", "banana", "avocado", "cherry", "blueberry"]
groups = defaultdict(list)
for word in words:
    groups[word[0]].append(word)

print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

# Count occurrences
counts = defaultdict(int)
for char in "hello world":
    counts[char] += 1
print(dict(counts))
Python dictionary key-value pairs
Note: Dictionary keys must be immutable types (strings, numbers, tuples of immutables). Lists and dictionaries cannot be used as keys. As of Python 3.7, dictionaries preserve insertion order.

Practice Exercise

Create a nested dictionary representing a phonebook with at least 5 contacts. Each contact has name, phone, email, and groups (list). Write code to: (1) find all contacts in a given group, (2) update a contact's phone number, (3) add a new contact, (4) print all contacts sorted by name, and (5) use a defaultdict to group contacts by their first letter.