Lesson 26 of 55
8 mins readPython Iterating Hashes: keys, values & each
In Plain English
The `keys %hash` function returns a list of all keys, `values %hash` returns all values, and `while (my ($k, $v) = each %hash)` iterates pairs efficiently.
Deep Dive: How It Works
keys %hash: Returns an array of keys (often sorted: `sort keys %hash`).
values %hash: Returns an array of corresponding values.
each %hash: Iterator yielding `($key, $value)` pairs one by one in a while loop.
Core Rules to Remember

keys %hash: Returns all keys as a list for iteration.

each %hash Iterator: Efficient for large hashes without building intermediate lists in memory.
Live Interactive Example
Hit Run Code to see it liveIterating Hash Keys and Pairs
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: sort keys %scores ordered the students alphabetically before lookup.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Print Total Number of Keys
Declare `%inventory = ( apples => 10, oranges => 5, berries => 20 );`
Print `"Inventory categories: " . scalar(keys %inventory) . "\n"`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.