Quest 1 • Lesson 8
📚 Dictionaries (key‑value pairs)
A dictionary stores data in key‑value pairs. Each key must be unique and immutable (string, number, tuple). Dictionaries are mutable – you can add, remove, or update items.
"Think of a dictionary like a real dictionary – you look up a word (key) to find its definition (value)."
dict_create.py
# Empty dictionary
empty = {}
# Dictionary with initial values
person = {
"name": "Alice",
"age": 30,
"city": "Lahore"
}
empty = {}
# Dictionary with initial values
person = {
"name": "Alice",
"age": 30,
"city": "Lahore"
}
dict_access.py
person = {"name": "Alice", "age": 30}
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("country", "Unknown")) # Unknown
print(person["name"]) # Alice
print(person.get("age")) # 30
print(person.get("country", "Unknown")) # Unknown
🔑 Accessing Values
dict[key]– raisesKeyErrorif key missing.dict.get(key, default)– returnsNoneor default if missing.
dict_update.py
person = {"name": "Alice", "age": 30}
# Add new key
person["city"] = "Lahore"
# Update existing key
person["age"] = 31
# Remove a key
del person["city"]
# or
age = person.pop("age") # removes and returns value
# Add new key
person["city"] = "Lahore"
# Update existing key
person["age"] = 31
# Remove a key
del person["city"]
# or
age = person.pop("age") # removes and returns value
🔄 Iterating Over Dictionaries
person = {"name": "Alice", "age": 30, "city": "Lahore"}
# Iterate over keys
for key in person:
print(key, person[key])
# Iterate over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Get all keys / values
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 30, 'Lahore'])
# Iterate over keys
for key in person:
print(key, person[key])
# Iterate over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Get all keys / values
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 30, 'Lahore'])
🧪 Interactive Playground
Enter a key and value to add/update the dictionary below.
{ }
Current dictionary will appear above.
✨ Challenge: Word Counter
Write a function count_words(text) that returns a dictionary of word frequencies. Example: count_words("hello world hello") → {"hello": 2, "world": 1}.
def count_words(text):
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
print(count_words("hello world hello")) # {'hello': 2, 'world': 1}
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
print(count_words("hello world hello")) # {'hello': 2, 'world': 1}
❤️ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
☕ Buy Me a Coffee➡️ Ready for more?
Next lesson: Error Handling (try/except) – make your code robust.
Continue to Lesson 1.9 →(Coming soon – check back or buy Pro Pack for instant access)