π’ Lesson 2 β Intermediate Level
πΉ Python Dictionaries: Storing and Accessing Key-Value Data

π° What Is a Dictionary?
A dictionary in Python is a data structure that stores data in key-value pairs, like this:
pythonCopierModifierperson = {
"name": "Ali",
"age": 25,
"city": "Rabat"
}
Each entry has:
- A key (like
"name"
) - A value (like
"Ali"
)
π Dictionaries use curly braces {}
, and keys must be unique.
π§© Why Use Dictionaries?
- π Easy to look up values using a key.
- β Better for structured data (e.g. profiles, settings).
- β‘ Faster than lists for some types of lookup operations.
β Creating a Dictionary
pythonCopierModifierstudent = {
"name": "Sara",
"grade": "A",
"age": 18
}
π Accessing Values
pythonCopierModifierprint(student["name"]) # Output: Sara
print(student["grade"]) # Output: A
π₯ β οΈ If the key doesnβt exist, Python will raise a KeyError
.
β
Safer way using .get()
:
pythonCopierModifierprint(student.get("email", "Not provided"))
ποΈ Adding or Updating Entries
pythonCopierModifierstudent["email"] = "sara@example.com" # Add new key
student["grade"] = "A+" # Update value
β Removing Items
pythonCopierModifierstudent.pop("age")
print(student)
β Or delete by key:
pythonCopierModifierdel student["email"]
π Looping Through a Dictionary
π Loop through keys:
pythonCopierModifierfor key in student:
print(key, "β", student[key])
π Loop through key-value pairs:
pythonCopierModifierfor key, value in student.items():
print(f"{key}: {value}")
π Loop through just values:
pythonCopierModifierfor value in student.values():
print(value)
π§ Dictionary Functions Summary:
Function | What It Does |
---|---|
dict.get(key, default) | Returns value or default if key missing |
dict.items() | Returns key-value pairs |
dict.keys() | Returns all keys |
dict.values() | Returns all values |
dict.pop(key) | Removes a key |
key in dict | Checks if a key exists |
π§ͺ Exercise 1:
Write a program that:
- Creates a dictionary called
contact
. - Asks the user to enter a name, phone, and email.
- Stores them as key-value pairs.
- Then prints the full contact information.
pythonCopierModifiercontact = {}
contact["name"] = input("Enter your name: ")
contact["phone"] = input("Enter your phone number: ")
contact["email"] = input("Enter your email address: ")
print("\nπ Contact Information:")
for key, value in contact.items():
print(f"{key.capitalize()}: {value}")
π§ͺ Exercise 2 (Challenge):
Create a simple program to store multiple students and their grades.
pythonCopierModifierstudents = {}
for i in range(3):
name = input(f"Enter student {i+1}'s name: ")
grade = input(f"Enter {name}'s grade: ")
students[name] = grade
print("\nπ Student Grades:")
for name, grade in students.items():
print(f"{name}: {grade}")
π Summary:
- Dictionaries store data in key-value pairs and are perfect for structured data.
- You can add, update, remove, and access values by their key.
- Looping over dictionaries is useful for displaying or processing structured data.