You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Dictionaries and sets are two more essential Python data structures. A dictionary stores data as key-value pairs — like a real dictionary maps words to definitions. A set stores unique, unordered elements — useful for membership testing and eliminating duplicates.
# Curly braces with key: value pairs
student = {
"name": "Alice",
"age": 20,
"grade": "A",
"courses": ["Maths", "Physics"]
}
# dict() constructor
config = dict(host="localhost", port=8080, debug=True)
# Empty dictionary
empty = {}
print(student)
print(config)
student = {"name": "Alice", "age": 20, "grade": "A"}
# Square bracket notation
print(student["name"]) # Alice
# .get() — returns None (or a default) instead of raising an error
print(student.get("age")) # 20
print(student.get("email")) # None
print(student.get("email", "N/A")) # N/A — custom default
# Square brackets raise KeyError for missing keys
# print(student["email"]) # KeyError: 'email'
student = {"name": "Alice", "age": 20}
# Add a new key-value pair
student["email"] = "alice@example.com"
# Modify an existing value
student["age"] = 21
# update() — merge another dictionary
student.update({"grade": "A", "age": 22})
print(student)
# {'name': 'Alice', 'age': 22, 'email': 'alice@example.com', 'grade': 'A'}
# Merge with | operator (Python 3.9+)
defaults = {"theme": "dark", "language": "en"}
user_prefs = {"theme": "light"}
settings = defaults | user_prefs
print(settings) # {'theme': 'light', 'language': 'en'}
student = {"name": "Alice", "age": 20, "grade": "A", "email": "alice@example.com"}
# del — delete a specific key
del student["email"]
# pop() — remove and return a value
grade = student.pop("grade")
print(grade) # A
print(student) # {'name': 'Alice', 'age': 20}
# pop() with default — no error if key missing
result = student.pop("phone", "not found")
print(result) # not found
# popitem() — remove and return the last inserted item
student["city"] = "London"
last = student.popitem()
print(last) # ('city', 'London')
# clear() — remove all items
student.clear()
print(student) # {}
student = {"name": "Alice", "age": 20, "grade": "A"}
# Loop through keys (default)
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# name: Alice
# age: 20
# grade: A
student = {"name": "Alice", "age": 20, "grade": "A"}
# keys(), values(), items()
print(list(student.keys())) # ['name', 'age', 'grade']
print(list(student.values())) # ['Alice', 20, 'A']
print(list(student.items())) # [('name', 'Alice'), ('age', 20), ('grade', 'A')]
# Check if a key exists
print("name" in student) # True
print("email" in student) # False
# setdefault() — get value or set it if missing
student.setdefault("email", "unknown")
print(student["email"]) # unknown
# Create a dictionary from a loop
squares = {x: x**2 for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Filter a dictionary
scores = {"Alice": 85, "Bob": 62, "Charlie": 91, "Diana": 78}
high_scores = {name: score for name, score in scores.items() if score >= 80}
print(high_scores) # {'Alice': 85, 'Charlie': 91}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.