Skip to content
AgileLogics
5 min read

Dictionaries

Prerequisites: Lists

A dictionary stores key/value pairs — instead of numbered positions like a list, each value has a named key.

Syntax

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

Example

print(user["name"])
user["age"] = 26
for key, value in user.items():
    print(key, value)

Expected output

Ada
name Ada
age 26

.items() gives both the key and value together, ready to loop over.

Common mistakes

  • Accessing a key that doesn't exist raises KeyError. Use user.get("email") instead, which returns None rather than crashing if the key is missing.

Practice

Create a dictionary representing a book with title and author keys, then print "{title} by {author}".

Show solution
book = {"title": "Dune", "author": "Frank Herbert"}
print(f"{book['title']} by {book['author']}")