Dictionaries Key Value Pairs, Accessing, Updating

Learn how to use dictionaries in Python – the perfect way to store related data like names and phone numbers, student scores, or product prices. You’ll master creating dictionaries, getting values, changing values, and adding new items.

Full Lesson Content (text + code)

What is a Dictionary?

A dictionary is a collection of key-value pairs.

  • Keys are unique (like labels or IDs)
  • Values can be anything: numbers, strings, lists, even other dictionaries
  • Dictionaries are written with curly braces {}
  • Keys and values are separated by a colon :

Python

# Example of a simple dictionary
person = {
    "name": "Jefferson",
    "age": 25,
    "city": "Lagos",
    "is_student": True
}

Think of it like a real dictionary: the word (key) → the definition (value).

Creating a Dictionary

Python

# Empty dictionary
empty_dict = {}

# Dictionary with items
student = {
    "name": "Aisha",
    "matric_no": "CS2023001",
    "score": 85,
    "courses": ["Python", "Data Structures"]
}

# Another way: using dict() function
phone_book = dict(name="Chinedu", phone="08012345678", city="Port Harcourt")

Accessing Values

Use square brackets [] with the key:

Python

print(student["name"])      # Output: Aisha
print(student["score"])     # Output: 85
print(student["courses"])   # Output: ['Python', 'Data Structures']

Important: If the key doesn’t exist → you get a KeyError

Python

# This will crash!
# print(student["phone"])   # KeyError: 'phone'

Safer way: Use .get() method (returns None if key not found)

Python

print(student.get("phone"))          # Output: None
print(student.get("phone", "Not found"))  # Output: Not found (custom default)

Updating / Changing Values

Just assign a new value to the key:

Python

student["score"] = 92           # Update existing value
print(student["score"])         # Now 92

student["grad_year"] = 2027     # Add a new key-value pair
print(student)

Other Useful Dictionary Methods

Python

# Add or update multiple items at once
student.update({"age": 22, "department": "Computer Science"})

# Delete a key-value pair
del student["grad_year"]
# OR
student.pop("age")              # Removes and returns the value

# Get all keys
print(student.keys())           # dict_keys(['name', 'matric_no', 'score', ...])

# Get all values
print(student.values())

# Get all key-value pairs
print(student.items())          # Returns list of tuples: [('name', 'Aisha'), ...]

# Check if a key exists
if "name" in student:
    print("Name is in the dictionary!")

Quick Mini-Exercise (Add this as a text block or assignment)

Create a dictionary for your favorite football player and update one value:

Python

player = {
    "name": "Osimhen",
    "club": "Napoli",
    "goals": 15,
    "position": "Striker"
}

# Your task:
# 1. Print the player's club
# 2. Update goals to 25
# 3. Add a new key "country" with value "Nigeria"
# 4. Print the final dictionary

Expected output:

Python

Napoli
{'name': 'Osimhen', 'club': 'Napoli', 'goals': 25, 'position': 'Striker', 'country': 'Nigeria'}

Lesson Tips for LearnDash

  • Video suggestion: 8–12 minutes – show live coding in VS Code, explain each example.
  • Add code snippets: Use the Code block in Gutenberg for syntax highlighting.
  • Completion requirement: Mark as complete when student views + mark quiz (see below).
  • Downloadable material: Provide a .py file with all examples + the exercise.

Quiz Ideas (Add a LearnDash Quiz after this lesson)

  1. What symbol is used to separate keys and values in a dictionary? a) = b) : c) , d) ; Answer: b
  2. How do you access the value of key “age” in dict person? person[“age”]
  3. What happens if you try to access a key that doesn’t exist with [] ? KeyError
  4. Which method is safe to use when accessing a key that might not exist? .get()
  5. How do you add a new key-value pair? dict[“new_key”] = value