Skip to content

Python Dictionaries

Key-value mappings with dicts: creation, access, methods, iteration, and nested structures.

What you'll learn

  • Create dictionaries and access values by key
  • Add, update, and delete key-value pairs
  • Iterate over keys, values, and items
  • Use get(), setdefault(), and dict comprehensions
  • Work with nested dictionaries

Concept

Creating Dictionaries

A dictionary (dict) is an unordered collection of key-value pairs. Keys must be hashable (immutable types like str, int, tuple), and each key is unique:

empty = {}
user = {"name": "Ada", "age": 25, "role": "admin"}
scores = dict(math=90, science=85, english=88)

Dictionaries are Python's most powerful data structure for lookups — accessing a value by key is O(1) on average. They are the natural representation for JSON, configuration, and any named-field data.

Accessing and Modifying

user = {"name": "Ada", "age": 25}

# Access — KeyError if key missing
print(user["name"])        # Ada

# Safe access with get() — returns None or a default
print(user.get("email"))            # None
print(user.get("email", "N/A"))     # N/A

# Add or update a key
user["email"] = "ada@example.com"
user["age"] = 26  # update existing

# Delete
del user["email"]
user.pop("age")   # remove and return value

Always use .get() when a key might be missing — it avoids KeyError and lets you specify a default. This is one of the most important dict patterns.

Iterating

user = {"name": "Ada", "age": 25, "role": "admin"}

# Keys only
for key in user:
    print(key)

# Keys and values together
for key, value in user.items():
    print(f"{key} = {value}")

# Values only
for value in user.values():
    print(value)

The .items() method is the most useful — it lets you loop over key-value pairs simultaneously. In Python 3.7+, dictionaries maintain insertion order, so iteration is predictable.

Useful Methods

  • .get(key, default) — safe access with a fallback
  • .setdefault(key, default) — get or set in one operation
  • .update() — merge another dict
  • .keys() / .values() / .items() — view objects
  • in — check if a key exists
config = {"debug": False}
config.setdefault("port", 8080)   # adds port only if missing
config.update({"debug": True, "host": "localhost"})
print("port" in config)           # True

Dict Comprehensions

Just like list comprehensions, but for dictionaries:

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

prices = {"apple": 1.5, "banana": 0.5}
doubled = {k: v * 2 for k, v in prices.items()}

Nested Dictionaries

Dictionaries can be nested to represent structured data:

users = {
    "ada": {"age": 25, "role": "admin"},
    "bob": {"age": 30, "role": "user"},
}
print(users["ada"]["role"])  # admin

For deeply nested structures, consider collections.defaultdict or data classes for cleaner access.

Example

              # Creating dictionaries
user = {"name": "Ada", "age": 25, "role": "admin"}
scores = dict(math=90, science=85, english=88)

# Accessing — use get() for safety
print(user["name"])              # Ada
print(user.get("email"))         # None
print(user.get("email", "N/A"))  # N/A

# Adding and updating
user["email"] = "ada@example.com"
user["age"] = 26
print(user)

# Iterating
for key, value in user.items():
    print(f"  {key} = {value}")

# Useful methods
config = {"debug": False}
config.setdefault("port", 8080)
config.update({"host": "localhost"})
print(config)

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

# Nested dictionaries
users = {
    "ada": {"age": 25, "role": "admin"},
    "bob": {"age": 30, "role": "user"},
}
print(users["ada"]["role"])  # admin

# Deleting
del user["email"]
print(user.pop("age"))  # 26
print(user)
            

Demonstrates dict creation, safe access with get(), adding/updating/deleting keys, iteration with items(), setdefault and update, dict comprehensions, and nested dict access.

Try it

  • JSON Formatter

    Python dicts map directly to JSON objects — format and validate them.

  • CSV to JSON

    Converting CSV rows to dicts is a common data transformation.

Common mistakes

The mistake

Accessing a missing key with dict[key] instead of dict.get(key)

The fix

dict[key] raises KeyError if the key does not exist. Use dict.get(key) which returns None, or dict.get(key, default) to specify a fallback. This is the safest access pattern.

The mistake

Using a list as a dictionary key

The fix

Dictionary keys must be hashable (immutable). Lists and dicts are not hashable — use a tuple instead. frozenset can be used as a key if you need a set-like key.

Related Snippets

Related Cheatsheets

Practice Python Dictionaries

10 exercises

Practice Python Dictionaries

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors