Learn Without Walls
← Module 8 Home Lesson 1 of 4 Next Lesson →

Lesson 8.1: Creating and Using Dictionaries

What You'll Learn

1. What is a Dictionary?

A dictionary is a collection of key-value pairs. Think of it like a real dictionary: you look up a word (the key) and get a definition (the value). In Python, you can look up any key and get the value associated with it.

Dictionary: An unordered, mutable collection that maps keys to values. Each key must be unique within a dictionary. Created using curly braces {} or the dict() constructor.

Unlike lists, which use numeric indices (0, 1, 2...), dictionaries use meaningful keys to organize data:

# A list uses numeric indices
student_list = ["Alice", 20, "Computer Science"]
# What does index 1 mean? Hard to tell!

# A dictionary uses descriptive keys
student_dict = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}
# Much clearer what each value represents!

2. Creating Dictionaries

There are several ways to create a dictionary in Python:

Using Curly Braces (Most Common)

# Empty dictionary
empty = {}

# Dictionary with key-value pairs
person = {
    "name": "Maria",
    "age": 25,
    "city": "Los Angeles"
}

print(person)
print(type(person))
{'name': 'Maria', 'age': 25, 'city': 'Los Angeles'} <class 'dict'>

Using the dict() Constructor

# Using keyword arguments
person = dict(name="Maria", age=25, city="Los Angeles")

# From a list of tuples
colors = dict([("red", "#FF0000"), ("green", "#00FF00")])

print(person)
print(colors)
{'name': 'Maria', 'age': 25, 'city': 'Los Angeles'} {'red': '#FF0000', 'green': '#00FF00'}
Key Rules: Dictionary keys must be immutable types (strings, numbers, tuples). You cannot use lists or other dictionaries as keys. Keys must also be unique — if you repeat a key, the last value wins.
# Keys must be unique - last value wins
grades = {"math": 90, "math": 95}
print(grades)  # {'math': 95} - the 90 is overwritten

# Values can be any type
mixed = {
    "name": "Bob",
    "scores": [85, 92, 78],
    "passed": True,
    "gpa": 3.5
}

3. Accessing Values

You access dictionary values by placing the key inside square brackets:

student = {
    "name": "Carlos",
    "age": 22,
    "major": "Biology"
}

print(student["name"])
print(student["age"])
print(student["major"])
Carlos 22 Biology

KeyError: When a Key Doesn't Exist

If you try to access a key that does not exist, Python raises a KeyError:

student = {"name": "Carlos", "age": 22}

# This will cause a KeyError!
print(student["gpa"])
KeyError: 'gpa'

The get() Method: Safe Access

The get() method returns None (or a default value you choose) instead of raising an error:

student = {"name": "Carlos", "age": 22}

# Returns None if key doesn't exist
print(student.get("gpa"))

# You can provide a default value
print(student.get("gpa", 0.0))

# Works normally for keys that exist
print(student.get("name"))
None 0.0 Carlos

When to Use get() vs Square Brackets

Use square brackets dict[key] when you are certain the key exists and want an error if it does not (a bug you want to catch early).

Use get() when the key might not exist and you want to handle that gracefully with a default value.

4. Adding and Updating Entries

Dictionaries are mutable, so you can add new key-value pairs or change existing values at any time:

profile = {"name": "Dana"}

# Add new keys
profile["age"] = 28
profile["email"] = "dana@example.com"
print(profile)

# Update existing key
profile["age"] = 29
print(profile)
{'name': 'Dana', 'age': 28, 'email': 'dana@example.com'} {'name': 'Dana', 'age': 29, 'email': 'dana@example.com'}

The syntax is the same for adding and updating. Python checks: if the key already exists, it updates the value. If the key is new, it adds the pair.

5. Removing Entries

There are several ways to remove key-value pairs from a dictionary:

inventory = {
    "apples": 5,
    "bananas": 3,
    "oranges": 8,
    "grapes": 12
}

# del removes a key-value pair
del inventory["bananas"]
print(inventory)

# pop() removes and returns the value
count = inventory.pop("oranges")
print(f"Removed oranges: {count}")
print(inventory)

# pop() with default avoids KeyError
count = inventory.pop("mangoes", 0)
print(f"Removed mangoes: {count}")
{'apples': 5, 'oranges': 8, 'grapes': 12} Removed oranges: 8 {'apples': 5, 'grapes': 12} Removed mangoes: 0

6. Checking if a Key Exists

Use the in keyword to check whether a key exists in a dictionary:

menu = {
    "coffee": 3.50,
    "tea": 2.75,
    "water": 1.00
}

print("coffee" in menu)
print("juice" in menu)
print("juice" not in menu)

# Common pattern: check before accessing
item = "coffee"
if item in menu:
    print(f"{item} costs ${menu[item]:.2f}")
else:
    print(f"Sorry, {item} is not on the menu")
True False True coffee costs $3.50
Important: The in operator checks keys, not values. To check if a value exists, use value in dict.values().

Check Your Understanding

Question: What will the following code print?

info = {"x": 10, "y": 20}
info["z"] = 30
info["x"] = 99
print(len(info))
print(info.get("w", 0))

Answer:

3 — the dictionary has keys "x", "y", and "z" (updating "x" does not add a new key).

0 — key "w" does not exist, so get() returns the default value 0.

Try It Yourself

Create a dictionary called contact with keys "name", "phone", and "email". Then:

  1. Print the person's name
  2. Add a "city" key
  3. Update the phone number
  4. Use get() to safely access a "website" key with a default of "N/A"

Key Takeaways

← Module 8 Home Next: Dictionary Methods →