🗂️

How to Use Dictionaries in Python

PythonBeginner

Store key-value pairs for fast lookups.

Code Example

Python
# Dictionaries in Python
student = {
    "name": "Alice",
    "age": 22,
    "grades": [90, 85, 92],
    "active": True
}

# Access values
print(f"Name: {student['name']}")
print(f"Grades: {student['grades']}")

# Add/modify
student["email"] = "alice@example.com"
student["age"] = 23

# Iterate
print("\nAll keys and values:")
for key, value in student.items():
    print(f"  {key}: {value}")

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(f"\nSquares dict: {squares}")

Explanation

Dictionaries store key-value pairs. Keys must be unique and immutable. Use .items(), .keys(), .values() for iteration.

Related Tutorials