๐ข 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.