Lesson 8: Lists, Tuples, and Sets in Python

1. What is a Dictionary in Python?
A dictionary in Python is a collection of key-value pairs.
- Keys must be unique and immutable (e.g., strings, numbers, tuples).
- Values can be of any data type.
- Dictionaries are unordered (Python 3.7+ maintains insertion order).
๐ Example:
student = {
"name": "Alice",
"age": 22,
"courses": ["Python", "Math"],
"graduated": False
}
print(student["name"]) # Output: Alice
2. Creating Dictionaries
You can create dictionaries in different ways:
# Using curly braces
person = {"name": "John", "age": 30}
# Using dict() constructor
person2 = dict(name="Jane", age=25)
print(person)
print(person2)
3. Accessing and Modifying Elements
student = {"name": "Alice", "age": 22}
# Accessing values
print(student["name"]) # Alice
print(student.get("age")) # 22
print(student.get("grade", "N/A")) # Returns "N/A" if key doesnโt exist
# Modifying values
student["age"] = 23
student["city"] = "New York" # Adds a new key-value pair
print(student)
4. Removing Elements
student = {"name": "Alice", "age": 22, "city": "New York"}
student.pop("age") # Removes age
del student["city"] # Removes city
student.clear() # Clears all elements
5. Useful Dictionary Methods
Method | Description | Example |
---|---|---|
keys() | Returns all keys | dict.keys() |
values() | Returns all values | dict.values() |
items() | Returns key-value pairs as tuples | dict.items() |
update() | Updates dictionary with another dictionary | dict.update(new_dict) |
popitem() | Removes last inserted key-value pair | dict.popitem() |
๐ Example:
student = {"name": "Alice", "age": 22}
print(student.keys()) # dict_keys(['name', 'age'])
print(student.values()) # dict_values(['Alice', 22])
print(student.items()) # dict_items([('name', 'Alice'), ('age', 22)])
6. Looping Through Dictionaries
student = {"name": "Alice", "age": 22, "city": "New York"}
# Looping keys
for key in student:
print(key, student[key])
# Looping items
for key, value in student.items():
print(f"{key} => {value}")
7. Nested Dictionaries
Dictionaries can contain other dictionaries.
students = {
"101": {"name": "Alice", "age": 22},
"102": {"name": "Bob", "age": 24}
}
print(students["101"]["name"]) # Output: Alice
8. Dictionary Comprehension
# Create dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}
9. Comparison: Dictionary vs. List
Feature | Dictionary | List |
---|---|---|
Data Storage | Key-value pairs | Ordered collection of values |
Access | O(1) average (by key) | O(n) (by searching element) |
Keys/Indexes | Keys (unique) | Integer indexes |
Use Case | When you need fast lookup by key | When you need ordered items |
10. Summary
- Dictionaries store key-value pairs.
- Keys are unique and immutable.
- Provides powerful methods like
keys()
,values()
,items()
. - Supports nested dictionaries and dictionary comprehensions.
- Best for scenarios requiring fast lookups and mapping relationships.