🌱BeginnerData Structures

Dictionaries

Key-value mappings Python's go-to structure for fast lookup, grouping, and structured data.

Overview

A dictionary (dict) is a mutable, unordered (in Python 3.7+ maintains insertion order) collection of key-value pairs. Each key maps to exactly one value, and keys must be unique and hashable (strings, numbers, and tuples are common key types; lists cannot be keys because they are mutable). Dictionaries are defined with curly braces: {"key": value, "key2": value2}. Access a value with dict[key] or the safer dict.get(key, default) which returns None (or a specified default) instead of raising a KeyError when the key doesn't exist. Dicts are the backbone of Python. Function keyword arguments (**kwargs) are passed as dicts, JSON data parses to dicts, and configuration objects almost always use dicts. Mastering dict operations is essential for real-world Python.

Key Points

  • •Create with {}: `person = {"name": "Alice", "age": 30}` or dict(name="Alice", age=30)
  • •Access: dict[key] (raises KeyError if missing); dict.get(key) (returns None if missing)
  • •Add/update: dict[key] = value creates the key if it doesn't exist, updates if it does
  • •Delete: del dict[key]; dict.pop(key) removes and returns the value
  • •Iterate: for key in d, for val in d.values(), for k, v in d.items()
  • •Keys must be hashable (strings, numbers, tuples) lists are NOT valid keys
  • •dict.get(key, default) is safer than dict[key] when key existence is uncertain

Examples

Creating and accessing dictionaries

person = {
    "name": "Alice",
    "age": 30,
    "city": "London"
}

print(person["name"])          # Alice
print(person.get("age"))       # 30
print(person.get("email"))     # None (key missing, no error)
print(person.get("email", "N/A"))  # N/A (custom default)

# Add and update
person["email"] = "alice@example.com"  # add new key
person["age"] = 31                     # update existing
print(person)

Iterating over a dictionary

scores = {"Alice": 95, "Bob": 82, "Carol": 91}

# Keys
for name in scores:
    print(name)

# Values
for score in scores.values():
    print(score)

# Key-value pairs (most common)
for name, score in scores.items():
    print(f"{name}: {score}")

Useful dict methods and patterns

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

# Check if key exists
print("apples" in inventory)     # True
print("grapes" in inventory)     # False

# Remove a key
del inventory["bananas"]
removed = inventory.pop("cherries")  # returns 12
print(removed)

# Merge two dicts (Python 3.9+: d1 | d2)
defaults = {"color": "blue", "size": 10}
custom = {"size": 20, "font": "Arial"}
merged = {**defaults, **custom}   # custom overrides defaults
print(merged)  # {'color': 'blue', 'size': 20, 'font': 'Arial'}

Common Mistakes

  • Using dict[key] when the key might not exist use dict.get(key) or check `if key in dict` first
  • Iterating over a dict while modifying it iterate over a copy: `for k in list(d.keys()):`
  • Using a mutable type (like a list) as a key raises TypeError: unhashable type

Note

dict.setdefault(key, default) is handy for grouping: if the key doesn't exist it sets it to the default and returns it; if it does exist it returns the existing value. `groups.setdefault(category, []).append(item)` is a common pattern.

Exercises

Write Python code to solve each exercise. Run it in your browser and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What is the difference between `d["key"]` and `d.get("key")`?