Python dict.items
Visit shelf labels and their counts together for a repeatable report.
A simple example
dict.items
- Start with B = 2, A = 1
- Do this Visit entries in key order
- Result A = 1, then B = 2
Syntax
sorted(stock.items())
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyPrint shelf totals in aisle order
A stockroom supervisor sends a short inventory message each evening. Both the aisle name and its count belong on each line, and the message must follow aisle order every time.
stock = {"B": 2, "A": 4}
print(", ".join(f"{aisle}={n}" for aisle, n in sorted(stock.items())))
A=4, B=2
Sorting the pairs by aisle places A before B.
Print stock by aisle
A delivery entered the second aisle before the first. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?
Print counts by room
A teacher recorded West before East during the count. The clerk sorts the keys before printing each key beside its associated value. What appears on the labels?
What to watch for
Dict iteration preserves insertion order. Sort the pairs when the report specifically needs aisle order.