Hone

Lessons · Python · looping over a dict

Walking a dict: keys, values, or both

for k in d gives keys; d.values() gives values; d.items() gives (key, value) pairs.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Config, counts, records by id: dicts hold most structured data, and you constantly need to walk them to report, total, or transform.

How to think about it

Do I need the keys, the values, or both? Ask what you need inside the loop. Only the names: keys. Only the numbers: values. Both, which is most of the time: items() with two loop variables.

Worked example

stock = {"pen": 3, "ink": 0}
Product to quantity.
for name, qty in stock.items():
Two names, because items() gives pairs.
    if qty == 0:
Use the value.
        print(name, "is out")
Use the key. 'ink is out'.

Your turn

Add up every quantity.

total = 0
for q in stock.():
    total += q

The trap

Changing a dict's size while looping over it raises an error. Collect the keys to delete first, then delete after the loop.

Next in Python

Every Python lesson on one page

Practise looping over a dict on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.