Menu

Dictionaries

Introduction

Dictionaries are Python's key-value data structure — incredibly useful and one of the most commonly used types in Python programming.

Dictionary basics

# Creating dictionaries
user = {
    "name": "Alice",
    "age": 30,
    "email": "alice@example.com"
}

# Accessing values
user["name"]           # "Alice"
user.get("phone", "N/A")  # "N/A" (default if key missing)

# Modifying
user["age"] = 31           # update
user["phone"] = "555-0123"  # add new key
del user["email"]           # delete key

# Iteration
for key in user:
    print(key, user[key])

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

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

# Useful methods
user.keys()    # dict_keys
user.values()  # dict_values
user.items()   # dict_items (key-value pairs)
"name" in user # True

Nested dictionaries

school = {
    "class_a": {
        "teacher": "Mr. Smith",
        "students": ["Alice", "Bob"]
    },
    "class_b": {
        "teacher": "Ms. Jones",
        "students": ["Charlie", "Diana"]
    }
}

print(school["class_a"]["teacher"])  # "Mr. Smith"

Assignment

  1. Create a dictionary that represents a book (title, author, year, genres as a list).
  2. Practice iterating over dictionaries using .items().
  3. Build a word-frequency counter using a dictionary.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!