Python Dictionaries: The Power of Key-Value Pairs


In real life, you often look things up using a label — like finding a contact in your phone using their name. In Python, a dictionary works the same way: it lets you store data as key-value pairs.

In this post, you’ll learn:

  • What dictionaries are
  • How to create and access dictionary data
  • How to update, delete, and loop through them
  • Real-life examples and tips

🧠 What Is a Dictionary?

A dictionary is a collection of key-value pairs. Each key is unique and maps to a value.

✅ Syntax:

my_dict = {
    "name": "Ada",
    "age": 25,
    "is_programmer": True
}

Here:

  • "name", "age", and "is_programmer" are keys
  • "Ada", 25, and True are values

🔍 Accessing Dictionary Values

Use the key name in square brackets or the .get() method:

print(my_dict["name"])         # Output: Ada
print(my_dict.get("age"))      # Output: 25

⚠️ Using .get() is safer — it returns None if the key doesn’t exist, instead of crashing.


✏️ Adding and Updating Values

my_dict["city"] = "Lagos"     # Add new key-value pair
my_dict["age"] = 26           # Update existing value


❌ Removing Items

my_dict.pop("is_programmer")  # Removes key "is_programmer"

Or remove the last item:

my_dict.popitem()


🔁 Looping Through a Dictionary

Loop through keys:

for key in my_dict:
    print(key)

Loop through keys and values:

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

Output:

name: Ada
age: 26
city: Lagos


🔄 Useful Dictionary Methods

MethodDescription
.keys()Returns all keys
.values()Returns all values
.items()Returns key-value pairs
.update({...})Adds or updates multiple items
.clear()Removes everything

🧪 Real-Life Example

📚 Student Info

student = {
    "name": "Grace",
    "scores": [85, 92, 78],
    "is_enrolled": True
}

# Calculate average score
average = sum(student["scores"]) / len(student["scores"])
print(f"{student['name']}'s average score is {average}")

Output:

Grace's average score is 85.0


🧭 Summary

  • Dictionaries store data as key-value pairs
  • Keys must be unique
  • You can add, update, delete, and loop through items easily
TaskExample
Create{"key": "value"}
Accessdict["key"] or dict.get()
Add/Updatedict["key"] = value
Removedict.pop("key")
Loopfor k, v in dict.items()

🚀 Try This

Create a dictionary for a book:

book = {
    "title": "The Python Journey",
    "author": "Jane Code",
    "pages": 250
}

Print:

  • The title
  • Add a “year”
  • Update the page count
  • Loop through and print everything

Leave a comment

Design a site like this with WordPress.com
Get started