Lesson 11 of 25

Dictionaries

Creating and Accessing Dictionaries

A dictionary is an unordered collection of key-value pairs. Each key maps to a value, like a real-world dictionary maps words to definitions. Dictionaries are defined using curly braces {}.

Keys must be unique and immutable (strings, numbers, or tuples). Values can be anything, including other dictionaries or lists.

Example
# Creating a dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "hobbies": ["reading", "coding"]
}

# Accessing values
print(person["name"])      # Alice
print(person.get("age"))   # 30
print(person.get("email", "N/A"))  # N/A (default if key missing)

# Adding and updating
person["email"] = "alice@example.com"  # Add new key
person["age"] = 31                     # Update existing key

# Removing entries
del person["city"]                     # Delete a key
removed = person.pop("email")          # Remove and return value
print(removed)  # alice@example.com

print(person)
# {'name': 'Alice', 'age': 31, 'hobbies': ['reading', 'coding']}
  • dict[key] — Access value (raises KeyError if key missing)
  • dict.get(key, default) — Access value (returns default if key missing)
  • dict[key] = value — Add or update a key-value pair
  • del dict[key] — Delete a key-value pair
  • dict.pop(key) — Remove a key and return its value
  • key in dict — Check if a key exists
Try Dictionaries
JavaScript
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

print("Name:", person["name"])
print("Age:", person.get("age"))

person["email"] = "alice@example.com"
print("Added email:", person["email"])

print("Has city?", "city" in person)
print("Keys:", list(person.keys()))
Notes
  • Use .get() instead of bracket notation when you're not sure if a key exists. It avoids KeyError exceptions and lets you provide a default value.

Dictionary Methods and Iterating

Dictionaries provide several useful methods for working with keys, values, and items. You can iterate over a dictionary's keys, values, or both simultaneously.

Dictionary comprehensions let you create dictionaries concisely, similar to list comprehensions.

Example
student = {"name": "Bob", "math": 92, "science": 88, "english": 95}

# Useful methods
print(student.keys())    # dict_keys(['name', 'math', 'science', 'english'])
print(student.values())  # dict_values(['Bob', 92, 88, 95])
print(student.items())   # dict_items([('name', 'Bob'), ('math', 92), ...])

# Iterating over keys
for key in student:
    print(f"{key}: {student[key]}")

# Iterating over key-value pairs
for key, value in student.items():
    print(f"{key} = {value}")

# Dictionary comprehension
numbers = [1, 2, 3, 4, 5]
square_dict = {n: n**2 for n in numbers}
print(square_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Merging dictionaries
defaults = {"color": "blue", "size": "medium"}
custom = {"color": "red", "weight": 10}
merged = {**defaults, **custom}
print(merged)  # {'color': 'red', 'size': 'medium', 'weight': 10}
Try Dictionary Iteration
JavaScript
scores = {"math": 92, "science": 88, "english": 95}

print("Subject scores:")
for subject, score in scores.items():
    print(f"  {subject}: {score}")

avg = sum(scores.values()) / len(scores)
print(f"Average: {avg:.1f}")

# Dictionary comprehension
squares = {n: n**2 for n in range(1, 6)}
print("Squares:", squares)
Notes
  • Since Python 3.7, dictionaries maintain insertion order. In earlier versions, order was not guaranteed.