SECTION 05 / 31

Loop through keys, then read their values

1 min read
keys(d) returns a list of keys. The course does not promise a sorted key order.
keys(d) returns a list of keys. The course does not promise a sorted key order.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Iterate through keys, then read values

Follow the dictionary as its keys and values change. Predict each lookup or update before revealing the next step.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next key, whether it already exists, and the value that will be stored.

foreach k in keys(d) {
    value = d[k]
    # use k and value
}

Do not assume dictionary keys come out in the order they were inserted, in number order, or in alphabetical order. Our visual table chooses a readable display order; that is not a pseudocode guarantee. If a task needs sorted keys, extract keys(d) and sort that LIST using an explicit comparator.

The resulting list of keys lets you use familiar list operations. length(keys(d)) counts distinct entries. It does not count all original records if several records were accumulated under the same key.

Try it yourself

If d={Chennai:8,Madurai:5}, what does length(keys(d)) count?

Show explained answer

Two city keys. It does not report the 13 student records represented by those values.

Try it yourself

Can summing all dictionary values depend on key order?

Show explained answer

For these exact integer counts, no. Each value contributes once regardless of order.

Try it yourself

Does a displayed row order prove keys(d) is sorted?

Show explained answer

No. It is only a display choice unless the algorithm explicitly sorts the key list.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑