1. What are Dictionaries? The Basics
A dictionary is an unordered (pre-Python 3.7) or insertion-ordered (Python 3.7+), mutable collection of items. Each item is a key-value pair.
- Keys: Must be unique and immutable. Common key types are strings, numbers (integers, floats), and tuples. Lists cannot be keys.
- Values: Can be anything (strings, numbers, lists, other dictionaries, etc.). Values do not have to be unique.
- Mutable: You can add, remove, and modify key-value pairs after a dictionary is created.
- Insertion-Ordered (Python 3.7+): While historically unordered, modern Python guarantees that dictionary items retain the order in which they were added.
Syntax: Dictionaries are created using curly braces `{}`, with key-value pairs separated by colons, and pairs separated by commas.
# An empty dictionary
empty_dict = {}
# Dictionary with string keys (UdaanPath profile)
user_profile = {
"name": "Alice",
"age": 30,
"city": "New York",
"is_active": True
}
# Dictionary with mixed key types (less common but possible)
mixed_keys = {
"status_code": 200,
1: "success",
(1, 2): "coordinates" # A tuple as a key (tuples are immutable!)
}
# Dictionary with list as a value
student_grades = {
"John": [90, 85, 92],
"Jane": [78, 88, 95]
}
print(f"Empty dict: {empty_dict}")
print(f"User Profile: {user_profile}")
print(f"Mixed Keys: {mixed_keys}")
print(f"Student Grades: {student_grades}")
print(f"Type of 'user_profile': {type(user_profile)}")
Empty dict: {} User Profile: {'name': 'Alice', 'age': 30, 'city': 'New York', 'is_active': True} Mixed Keys: {'status_code': 200, 1: 'success', (1, 2): 'coordinates'} Student Grades: {'John': [90, 85, 92], 'Jane': [78, 88, 95]} Type of 'user_profile': <class 'dict'>