What they are
A dictionary stores pairs of keys and values. You look up values by their key, like a real dictionary where you look up a word (key) to find its definition (value).
Basic syntax
# Create a dictionary:
person = {
'name': 'Alice',
'age': 30,
'city': 'NYC'
}
# Access values:
print(person['name']) # 'Alice'
print(person['age']) # 30
Adding and modifying
person = {'name': 'Alice'}
# Add new key-value pair:
person['age'] = 30
# Modify existing:
person['name'] = 'Bob'
print(person) # {'name': 'Bob', 'age': 30}
Safe access with .get()
Use .get() to avoid KeyError if key doesn't exist:
person = {'name': 'Alice'}
# Risky:
# city = person['city'] # KeyError if 'city' doesn't exist
# Safe:
city = person.get('city', 'Unknown') # Returns 'Unknown' if key missing
print(city) # 'Unknown'
Common operations
person = {'name': 'Alice', 'age': 30}
# Check if key exists:
if 'name' in person:
print(person['name'])
# Get all keys:
keys = person.keys() # dict_keys(['name', 'age'])
# Get all values:
values = person.values() # dict_values(['Alice', 30])
# Get all items:
items = person.items() # dict_items([('name', 'Alice'), ('age', 30)])
When to use dictionaries
- Storing related data (like a person's info)
- Fast lookups by key (O(1) average time)
- Mapping one value to another (like word → definition)
- Counting occurrences (use key as item, value as count)