Tutorials / Python Basics / Lesson 12

Dictionaries

What You Will Learn

A dictionary stores data as key-value pairs. Instead of looking up items by position (like a list), you look them up by name.


Creating a Dictionary

Use curly braces, with key: value pairs separated by commas:

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

print(person)
print(person["name"])
print(person["age"])

Expected output:

{'name': 'Alice', 'age': 25, 'city': 'London'}
Alice
25

Accessing Values

Use the key in square brackets:

person = {"name": "Alice", "age": 25}

print(person["name"])   # Alice

# Safe access with .get() — returns None if key doesn't exist
print(person.get("email"))          # None
print(person.get("email", "N/A"))   # N/A

Adding and Updating

person = {"name": "Alice", "age": 25}

person["email"] = "alice@example.com"  # add new key
person["age"] = 26                      # update existing key

print(person)

Expected output:

{'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}

Removing Items

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

del person["city"]
print(person)

age = person.pop("age")
print(f"Removed age: {age}")
print(person)

Expected output:

{'name': 'Alice', 'age': 25}
Removed age: 25
{'name': 'Alice'}

Checking if a Key Exists

person = {"name": "Alice", "age": 25}

if "name" in person:
    print("Has a name")

if "email" not in person:
    print("No email on file")

Expected output:

Has a name
No email on file

Looping Over a Dictionary

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

# Loop over keys
for key in person:
    print(key)

# Loop over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Expected output:

name
age
city
name: Alice
age: 25
city: London

A Real Example

# A simple contact book
contacts = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Carol": "carol@example.com",
}

name = input("Look up contact: ")

if name in contacts:
    print(f"{name}'s email: {contacts[name]}")
else:
    print(f"No contact found for {name}")

Example interaction:

Look up contact: Alice
Alice's email: alice@example.com

What You Learned

  • Dictionaries store key-value pairs
  • Access values with dict[key] or dict.get(key)
  • Add and update with dict[key] = value
  • Remove with del dict[key] or .pop(key)
  • Loop with .items() to get both key and value

In the next lesson, you will learn how to read and write files so your programs can save and load data.