SECTION 04 / 31

Check whether the key exists before reading it

1 min read
A present zero and a missing key are different. isKey tests the key, not the value’s truth.
A present zero and a missing key are different. isKey tests the key, not the value’s truth.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Check keys, including a missing key

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.

if (isKey(d,k)) {
    value = d[k]
}
else {
    # No value is stored for this key.
    # Decide whether to create an entry or report a missing key.
}

With d={7:0}, isKey(d,7) is True and d[7] is 0. isKey(d,99) is False. Do not assume a missing lookup automatically returns 0 or False in this pseudocode. The lab’s key 7 has a constructed zero specifically to demonstrate presence; it is not Aditya’s actual Chemistry mark.

keys(d) tells us the existing keys, not all possible keys. A present key may hold False, 0, [] or {}. None of these values makes the key disappear.

Try it yourself

For d={7:False}, isKey(d,7) True or False?

Show explained answer

True. The key exists even though its stored Boolean is False.

Try it yourself

Does isKey({7:76},76) test whether 76 is a stored value?

Show explained answer

No. It tests for a KEY 76, which is absent here.

Try it yourself

What happens on an empty dictionary membership search?

Show explained answer

No loop body executes and found remains False.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑