Lesson 5 of 15
Dictionaries
Dictionaries
A Python dictionary stores key-value pairs. Keys must be hashable (strings, numbers, tuples). Dictionaries preserve insertion order since Python 3.7.
Creating and Accessing
person = {"name": "Alice", "age": 30}
person["name"] # "Alice"
person.get("age") # 30
person.get("email", "") # "" (default if missing)
Mutating
person["email"] = "alice@example.com" # add/update
del person["age"] # delete key
Iterating
for key in person: # iterate keys
for key, val in person.items(): # iterate pairs
for val in person.values(): # iterate values
Useful Methods
person.keys() # dict_keys(['name', 'email'])
person.values() # dict_values(['Alice', 'alice@...'])
person.items() # dict_items([('name', 'Alice'), ...])
"name" in person # True
setdefault and defaultdict
d = {}
d.setdefault("count", 0) # set only if missing
d["count"] += 1
Your Task
Implement word_count(text) that returns a dictionary mapping each word to how many times it appears in text. Words are separated by spaces; treat them case-insensitively (lowercase all words).
Pyodide loading...
Loading...
Click "Run" to execute your code.