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'}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.