Lesson 4 of 5 · Collections · 2 min read · Updated
Working with dictionaries
Changing entries, looping over keys and values, counting, and dictionaries inside dictionaries.
python
stock = {"pen": 10, "book": 4}
stock["pencil"] = 25
stock["pen"] -= 3
del stock["book"]
print(stock)
for item, qty in stock.items():
print(item, qty)
print(list(stock.keys()))
print(stock.get("eraser", 0))
Output
{'pen': 7, 'pencil': 25}
pen 7
pencil 25
['pen', 'pencil']
0
- Assigning to a new key adds it; to an existing key, replaces its value.
del d[key]deletes;d.pop(key)deletes and gives the value back.d.items()gives key-value pairs to loop over;d.keys()andd.values()give one side.- Dictionaries remember the order keys were added.
The counting pattern
python
text = "banana"
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
Output
{'b': 1, 'a': 3, 'n': 2}
counts.get(ch, 0) gives the current count, or 0 the first time a letter is seen. This three-line loop counts anything — words, votes, marks in each grade.
Nested dictionaries
python
student = {"name": "Priya", "marks": {"maths": 90, "science": 85}}
print(student["marks"]["science"])
student.update({"city": "Salem"})
print(len(student))
print(student.pop("city"))
print("city" in student)
Output
85
3
Salem
False
Note
in on a dictionary checks the keys, not the values. Keys must be unchangeable values — strings, numbers or tuples — while values can be anything, including lists and other dictionaries.
d = {"a": 1}. What does d.get("b", 5) return?
Try this now
- Count how often each word appears in a sentence and print the words with their counts.
- Store a phone book as a dictionary; ask for a name and print the number, or "Not found".
Create a free account to save your progress, or sign in.