Lesson 17 of 55
9 mins readPython Generic for & pairs() Dictionary Iteration
In Plain English
`pairs(table)` iterates over **all** key-value associations in a table, regardless of key types or gaps. Keys are yielded in an unspecified hash order.
Deep Dive: How It Works
Universal Hash Iteration: Traverses string keys, integer keys, and object keys.
Unordered: Hash traversal order is determined by Lua internal hash bucket distribution.
pairs vs ipairs: Use `ipairs` for sequential arrays; use `pairs` for dictionary/hash maps.
Core Rules to Remember

pairs() for Dictionaries: Iterates every key-value pair in the table.

Unordered Traversal: Do not rely on insertion order when using `pairs()`.
Live Interactive Example
Hit Run Code to see it liveIterating Configuration Tables with pairs
Python 3.12
1
2
3
4
5
6
7
8
9
Output Console
Click "Run Code" to view the rendered output.
How it works: pairs traversed each field in the dictionary table.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Count Total Keys with pairs
Declare `local scores = { alice = 95, bob = 88, charlie = 92 }`.
Count total keys using `pairs` and print `"Total entries: " .. count`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.