Dictionaries
Python Dictionaries
Dictionaries store data as key-value pairs. They're perfect for representing structured data like a person's profile or settings.
python
person = {
"name": "Alice",
"age": 30,
"city": "NYC"
}
print(person["name"]) # Alice
print(person.get("age")) # 30Modifying Dictionaries
You can add, update, and remove key-value pairs easily.
python
person = {"name": "Alice", "age": 30}
person["email"] = "alice@example.com" # Add new key
person["age"] = 31 # Update value
del person["age"] # Delete key
print(person)Looping Through Dictionaries
You can iterate over keys, values, or both using dictionary methods.
python
scores = {"math": 95, "science": 87, "english": 92}
for subject, score in scores.items():
print(f"{subject}: {score}")Tip:Dictionary keys must be immutable (strings, numbers, tuples). Values can be anything — even other dictionaries!
PlaygroundPython
Output
Click "Run" to see output