VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

Ministry of Education V3.0 Reference 365 | G3 Computing Python Dictionaries: Find the Key, Update the Value, Explain the State

Researcher reviewing abstract data validation checks on a laptop beside a printed schema table

Did you know that assigning a new number to a Python dictionary can leave its number of entries unchanged? The outcome depends on the key. Assigning a value under a missing key adds a new association; assigning a value under an existing key replaces its previous value. This small distinction helps students understand computer state, accurate lookups and the cost of misunderstanding a program’s data.

Ministry of Education V3.0 Reference 365 teaches the 2027 Singapore–Cambridge SEC G3 Computing K349 dictionary operations in Module 2.3.10: insertion, query, lookup and deletion. It explains keys and values, assignments and replacements, missing-key errors, order of execution, parsing inputs, state-trace tables, and authentic student practice. Twenty-four original worked cases and a twelve-step checking process demonstrate how to justify dictionary behaviour rather than guess from the last line of code.

This is an independent eduKateSG educational resource, not an official MOE, SEAB or Cambridge document. The official 2027 K349 syllabus and Python quick-reference guide govern examinable scope. All example labels, counts and records are invented, and no real students’ personal or academic information is required to learn these operations.

1. Begin with the meaning of a key–value pair

A dictionary maps a key to an associated value. Consider d = {‘A’:4,’B’:7}. The strings ‘A’ and ‘B’ are keys; the numbers 4 and 7 are values. The braces enclose the dictionary, each colon separates a key from its value, and commas separate the entries. A lookup by ‘B’ returns 7.

A list uses numerical positions to select elements, but a dictionary uses the specified key. Do not assume that ‘B’ is automatically position one or that the order of the written literal creates a numerical index. The identity of the key is what makes the association meaningful. A strong beginner can point to both sides of every pair and explain which side is used for lookup.

2. The exact official 2027 K349 boundary

The syllabus lists dictionary insertion, query, lookup and deletion as programming operations students should be able to perform. Its quick-reference guide illustrates a dictionary with a key–value pair, assignment to a keyed expression, and deletion using del. These are the foundations of the written and lab examples.

The subject also includes variables, strings, lists, loops, selection, validation and debugging. Dictionaries often interact with those features, but the core task here is state: which keys exist now and what value does each one hold? A learner who can trace those facts can solve short exercises without needing an advanced database, third-party module or complicated method.

3. Look up the current value by key

With d = {‘A’:4,’B’:7}, the expression d[‘A’] evaluates to 4 and d[‘B’] evaluates to 7. The brackets do not mean ‘get the item at numbered position A’; they mean ‘use key A to retrieve its mapped value’. The same key can be looked up repeatedly without consuming the stored record.

A program may print a lookup or use the retrieved value in a calculation. A lookup on its own is not a state-changing operation. In a trace, distinguish an observation such as print(d[‘A’]) from an assignment such as d[‘A’] = 10. Confusing them leads to errors when a sequence contains several reads and modifications.

d = {"A": 4, "B": 7}
print(d["A"])  # 4
print(d["B"])  # 7

4. An assignment to a new key inserts an entry

If ‘C’ is absent from d, then d[‘C’] = 9 adds the association C→9. The earlier associations remain. A new key increases the number of pairs by one. Nothing about the numerical size of the value determines whether an insertion takes place.

A student can verify the result by comparing keys before and after the line. The important question is whether the key already existed at the time the assignment executed. A dictionary may contain large values or zero, but its entry count is based on unique keys, not the sum of the numbers being stored.

d = {"A": 4, "B": 7}
d["C"] = 9
print(d["C"])   # 9
print(len(d))   # 3

5. An assignment to an existing key replaces the value

Starting with {‘A’:4,’B’:7}, the assignment d[‘A’] = 11 updates A’s associated value to 11. The dictionary still has two keys, not three, because the same key is used. The prior value 4 no longer represents A’s current state.

For a trace question, record the state after every assignment. Do not preserve old entries in the imagined dictionary as though each assignment were a new row in a transaction log. A mapping stores the current association, not a full history of every previous value. A program that needs historical versions would have to design that separately.

6. del removes the key–value association

The statement del d[‘B’] removes key B and its value when B exists. A later direct bracket lookup d[‘B’] normally raises KeyError unless some earlier line reinserted the key. Deletion is different from assigning B the value 0: a key with value zero is still present.

This distinction matters for interpreting missing information. In a fictional stock dictionary, a product with count zero is known to have no units recorded. A product code with no entry has an unknown or absent record. The program should respond to each state according to its requirements rather than silently treating the two as identical.

d = {"A": 4, "B": 7}
del d["B"]
d["B"] = 12
print(d["B"])  # 12

7. A missing key does not automatically return zero

Direct indexing of a dictionary with a key that does not exist generally raises KeyError. Python does not assume every missing code means zero, and a missing value should not be invented. The special value None is also not the same as an absent key: assigning d[‘A’] = None keeps A in the mapping.

When debugging, first ask whether the code previously created the intended key. Check spelling, capitalisation and data type, then inspect any earlier deletion. A program might create a key only when a condition is True; a later unconditional lookup can then fail on paths where it was never inserted. The error is about the actual execution state.

8. Strings are case-sensitive keys

In ordinary Python dictionary use, ‘A’ and ‘a’ are different string keys. A program that inserts d[‘A’] and later requests d[‘a’] is not automatically requesting the same record. Likewise, the string ‘7’ and the integer 7 are distinct possible keys.

This is a useful connection to string processing. If input codes should ignore case, a program may normalise them consistently before insertion and lookup. However, that is a requirement decision. A case-sensitive identifier might deliberately distinguish two records. Avoid changing keys without first understanding what they represent.

9. The difference between a replacement and an accumulated total

Suppose a dictionary stores a fictional shelf’s current book count, with d[‘R1’] equal to 12. If five more books arrive, replacing the count with 5 is not the same as adding five to the current value. An accumulation rule requires retrieving the previous number and computing 12 + 5 = 17.

The dictionary itself does not decide whether a repeated record means a correction, a new measurement or an amount to accumulate. That rule comes from the problem specification. Students should identify the intended meaning of the stored values before selecting the assignment. This is one reason software requirements matter even in a tiny dictionary program.

10. Trace a sequence one statement at a time

Start with d = {‘x’:2}. Assign d[‘y’] = 3: two keys exist. Assign d[‘x’] = 8: x now maps to 8 while y remains 3. Delete y: one key remains. Looking up d[‘x’] returns 8. Each step follows the state created by the preceding steps.

A state trace should show line executed, keys present and values stored. The final print line may be simple, but an error earlier in the sequence changes its result. If a conditional branch or loop appears, only the statements actually executed change the dictionary. Do not read a source file as though every line of every branch must run.

d = {"x": 2}
d["y"] = 3
d["x"] = 8
del d["y"]
print(d["x"])  # 8

11. Values can be text and numbers

For labels = {‘A’:’ready’,’B’:’waiting’}, a lookup returns a string. For d = {‘A’:12}, it returns an integer. The dictionary structure is the same, but later operations depend on the value’s type. A numeric-looking string such as ’12’ is not automatically an integer 12.

If the question requires arithmetic, identify a suitable conversion only after checking the stored content. If the value is an identifier that must preserve leading zeros, leaving it as a string may be more appropriate. This connection between data structures and types is a frequent source of errors in longer practical programs.

12. len() can refer to the dictionary or its stored string

If d = {‘A’:’cat’,’B’:’dog’}, len(d) is 2 because it contains two entries. But len(d[‘A’]) is 3 because the stored value ‘cat’ has three characters. The two calls inspect different objects, and an answer must reflect which object is passed to the length function.

A student who treats len(d) as the total of numerical values or length of every key is misunderstanding the operation. The explicit argument determines what is measured. In a dictionary trace, check the difference between the mapping’s entry count and the type and length of a particular value.

13. File parsing can produce dictionary keys

A toy input line such as ‘R1,12’ can be split into a code and quantity, then stored in a dictionary. The dictionary does not check the file’s structure by itself. If a space or unexpected punctuation becomes part of the key, a later lookup may fail even though the assignment used valid Python syntax.

Strong data processing separates file reading, parsing, validation, dictionary assignment and output. A malformed record must not silently corrupt the mapping. For school practice, use invented records and clear assumptions; if a task guarantees valid input, state that assumption instead of adding unrequested complexity.

14. Duplicates require an explicit rule

A second record using the same key might be a replacement measurement, a count to add or an accidental duplicate. Assigning the new value directly implements replacement. Accumulation instead computes a new value from the existing one and the incoming amount. Rejecting duplicates requires yet another decision.

The correct operation depends on the requirement. A student should explain why two identical-looking assignments lead to a particular current value and whether that result matches the intended meaning. A dictionary will not independently determine whether a record is trustworthy or new.

15. Reading an entry does not remove it

The expression d[‘A’] retrieves the value and leaves the mapping intact. It is not a queue that consumes an item when accessed. A later lookup of A returns the same value unless a program has explicitly updated or deleted it in between.

This distinction is easily tested with a trace of two prints and one assignment. A print before replacement shows the earlier value, and a print after replacement shows the new one. Neither print itself changes the dictionary. Students should be able to locate the specific line responsible for the state transition.

16. Debug from the first incorrect state

Suppose a final lookup returns the wrong count. It may be tempting to change the print statement, but the error could originate from a repeated key that overwrote an earlier total. Check what the stored value was just before the print, then trace backwards to the assignment responsible for it.

If the key is missing, check whether insertion occurred on the actual code path, whether spelling or case changed, and whether a deletion removed it. A methodical trace distinguishes a syntax error, a missing-key runtime error and a logic error that stores the wrong value under a valid key.

17. Twelve-stage Key–Value–State learning protocol

This is an independent educational method rather than an official marking rubric. It reduces the cognitive load of dictionary questions by separating identification, modification, retrieval and verification. A learner can explain the state after every statement before predicting any output.

Stage 1 — Name the mapping

State what the key and its value mean in the fictional problem.

Stage 2 — Write the initial state

Record all initial key–value pairs exactly, without inventing entries.

Stage 3 — Verify key identity

Notice spelling, capitalisation and type; ‘A’ and ‘a’ are different keys.

Stage 4 — Identify a read

A bracket lookup returns an associated value without removing the entry.

Stage 5 — Identify insertion

Assignment to an absent key adds a new association.

Stage 6 — Identify replacement

Assignment to an existing key changes its value without adding another key.

Stage 7 — Identify deletion

del removes the association, not merely its numerical value.

Stage 8 — Update the trace

Write the current mapping after every statement that changes it.

Stage 9 — Follow branch conditions

Only operations on the executed path affect the dictionary’s state.

Stage 10 — Recognise missing keys

A direct lookup of a missing key normally raises KeyError.

Stage 11 — Check the output type

Distinguish a stored string from a stored number before arithmetic.

Stage 12 — Verify with a second example

Reorder the insert, update and delete operations to test whether your explanation transfers.

18. Twenty-four worked dictionary cases

Case 1 — Single association

d = {‘A’:3} holds one entry. d[‘A’] returns integer 3.

Case 2 — Two separate keys

d = {‘A’:3,’B’:7} holds two associations; looking up B returns 7.

Case 3 — New key insertion

From {‘A’:3}, d[‘C’] = 9 adds C→9 and increases the count to two.

Case 4 — Existing key update

From {‘A’:3}, d[‘A’] = 9 replaces the value; the entry count stays one.

Case 5 — Two updates

After d[‘A’] = 2 and d[‘A’] = 8, the current A value is 8, not two separate records.

Case 6 — Delete B

From {‘A’:3,’B’:7}, del d[‘B’] leaves A→3.

Case 7 — Reinsert B

After deleting B, assigning d[‘B’] = 12 makes the lookup of B valid again.

Case 8 — A value of zero

d = {‘A’:0} still contains key A. Zero does not mean absence.

Case 9 — Missing C

If only A exists, looking up C with brackets raises KeyError.

Case 10 — Different case

A key ‘A’ does not automatically match a lookup for ‘a’.

Case 11 — Different key types

The string key ‘5’ and integer key 5 can identify separate associations.

Case 12 — Read twice

Two successful lookups of d[‘A’] do not consume its value.

Case 13 — Count dictionary entries

len({‘A’:3,’B’:7}) is 2, not 10.

Case 14 — Count characters in a value

For {‘A’:’cat’}, len(d[‘A’]) is 3 while len(d) is 1.

Case 15 — Text replacement

Assigning d[‘A’] = ‘waiting’ replaces a previous string value ‘ready’.

Case 16 — Type-changing replacement

Assigning integer 12 replaces an old string ’12’ and changes the value’s type.

Case 17 — Conditional insertion

An insertion inside a branch that was not executed has no effect.

Case 18 — Conditional deletion

A deletion inside a skipped branch leaves the key unchanged.

Case 19 — Repeated assignment in a loop

Repeated assignment to the same key leaves the latest assigned value under one key.

Case 20 — Incorrect parsed key

A code with an unintended space may not match the originally stored code.

Case 21 — Replace on new measurement

If the requirement says newest reading wins, updating the same key is appropriate.

Case 22 — Accumulate a delivery

If R1 has 12 books and five arrive, a total-count rule requires 17, not replacement with 5.

Case 23 — Lookup after deletion

After deleting A, an unguarded direct lookup of A raises KeyError unless A was reinserted.

Case 24 — Four-operation trace

Start x→2, add y→3, set x→8, delete y; only x→8 remains.

19. Mini-project: a fictional shelf inventory

A teaching exercise stores counts for fictional shelf codes R1 and R2. The starting mapping is {‘R1′:12,’R2’:9}. A new shelf R3 is recorded with seven books. A later note describes five new arrivals for R1. The learner must decide whether to replace or increase the existing count based on the task’s exact meaning.

For a total-books requirement, R1 should become 17, R2 remains 9 and R3 is 7. A useful second test repeats the R3 key with a correction and explains whether it should update the stored value. The program should reject or account for unknown shelf codes according to a specified rule rather than manufacture a stock count.

20. Tutor and parent practice

Ask a student to draw three labelled boxes representing dictionary keys, place a number in each, and follow six instructions: read one, add one, replace one, delete one, attempt a missing lookup and reinsert it. The student should be able to state the whole mapping after every step.

Once the paper trace is accurate, use a Python learning environment to run a corresponding program with invented data. A tutor can inspect whether the student’s expectation matches the actual result and ask for an explanation. Parents can reinforce the key distinction—looking up is not updating—without needing to author any assessed code.

21. Frequently asked questions

What is a dictionary?

A mapping from unique keys to associated values.

Does assignment always create a new key?

No. An existing key’s value is replaced; a missing key is inserted.

Does a lookup remove the value?

No. Ordinary bracket lookup reads the current association.

Does zero mean the key is absent?

No. A key mapped to zero still exists.

What does del do?

It removes the specified key and its associated value.

What happens if a key does not exist?

Direct bracket lookup normally raises KeyError.

Are uppercase and lowercase keys equivalent?

No. ‘A’ and ‘a’ are different strings and can be separate keys.

Can a value be a string?

Yes. Values may have different types; later operations must respect them.

What does len(d) mean?

It counts the entries in the dictionary.

What improves accuracy most?

Trace each insertion, replacement and deletion before evaluating later lookups.

Extended practice: dictionary state, data quality and trace decisions

A dictionary question becomes difficult when students confuse the current mapping with the history of statements that produced it. The following exercises concentrate on deliberate updates, missing records and tested program decisions. They use invented shelf codes and labels so students can practise completely without accessing real people’s records.

How three assignments can produce only one current entry

Imagine an empty dictionary and the sequence d[‘A’] = 2; d[‘A’] = 5; d[‘A’] = 8. There are three assignment statements, but all of them use the same key. After the final statement, the dictionary holds one association, A→8. It would be inaccurate to describe the dictionary as containing values 2, 5 and 8 under three separate A keys. A variable storing an object’s current state is not necessarily a transaction log recording every historical revision.

Now add d[‘B’] = 1 and then delete A. The final mapping contains only B→1. If the student tries to print d[‘A’] after the deletion, the unguarded lookup raises KeyError. A question may show all these statements on one page; the correct solution depends on execution order rather than the number of times any key name is printed.

A data-format mismatch that looks like a failed lookup

A fictional school library identifies a shelf as ‘R01’. A file import accidentally reads the code as ‘R1’, leaving out the zero. Python treats these as different string keys even if the human operator intended the same shelf. The later expression d[‘R01’] cannot retrieve the value stored under ‘R1’ merely because the labels look similar. The mapping is behaving according to its defined equality rules.

To investigate, compare the exact key values and their data types; do not automatically change the retrieved value to zero. A correct fix might be to establish one canonical code format and validate incoming records before insertion. This teaches a transferable distinction: the data structure can operate correctly while upstream data quality causes a wrong practical result.

When replacing is right, and when it is not

Suppose the stored value d[‘R01’] is 12, representing the number of books currently on a shelf. A new note says that five books have been delivered. Replacing the value with 5 would lose the previous count; under a running-total requirement, the new count should be 17. A suitable computation uses the existing value and the increment. The dictionary supports the storage, but the task defines the arithmetic.

Change the story: the note instead says that a careful recount found only five books remaining. Now replacing the value with 5 may be correct. These two scenarios use identical numbers and the same key but have different expected results. A student must ask whether incoming data are an increment, a new full measurement or an error correction.

A missing key deserves an explicit decision

Consider a dictionary representing fictional sports-equipment quantities. It contains {‘cone’:0,’ball’:8}. Looking up ‘cone’ returns 0 because the entry is present. Looking up ‘net’ with direct bracket notation raises KeyError because no net entry exists. If the exercise needs to treat unknown items as zero, that must be part of the specified rule rather than an assumption made after the error.

More importantly, some tasks should reject unknown keys instead of creating new records. A student may learn to test whether a key is present before performing an operation, then follow an appropriate branch. The key pedagogical point is that there are multiple legitimate response policies and the requirements must decide among them.

A combined string-and-dictionary exercise

Suppose an invented input line is ‘B,7’. Splitting at the comma produces two strings: ‘B’ and ‘7’. The first is suitable as a label, while the second represents the characters of a number until it is converted. A dictionary assignment using the unconverted value can store the string ‘7’, and later arithmetic may not behave as the programmer expects.

Now consider ‘B,seven’ or ‘B,7,extra’. The first violates a numerical field expectation; the second creates three fields rather than two. Neither should be silently entered as a valid record. The file parsing stage checks structure, the conversion stage checks types, and the mapping stage stores the accepted association. Keeping these responsibilities separate improves debugging.

The difference between len(d) and arithmetic over values

The dictionary d = {‘A’:3,’B’:7,’C’:2} has three entries, so len(d) returns 3. Its values sum to 12, which is a separate calculation. A question asking for the number of categories is not asking for the total quantity across categories. These concepts can be confused when values themselves are small positive integers.

For a dictionary d = {‘A’:’cat’,’B’:’dog’}, len(d[‘A’]) is 3 because the value under A is a string of three characters, while len(d) is 2 because there are two entries. A robust answer names the object whose length is measured before producing the number. In programming, the argument to a function determines what is being processed.

What a trace table should show after every state change

A minimal state-trace table has three conceptual columns: executed statement, keys present, and current value under each key. Start with {‘x’:2}. After d[‘y’] = 3, record x→2 and y→3. After d[‘x’] = 8, record x→8 and y→3. After del d[‘y’], record only x→8. Printing x at the end yields 8.

Students should never skip the intermediate updates merely because they can see the final print. In a problem with a conditional or loop, a state table reveals whether a given assignment was actually executed. If the result is wrong, the first row where an incorrect state appears is usually more useful for debugging than guessing at the last statement.

Eight supplementary quick checks

A: d = {‘A’:1}; d[‘A’] = 4 leaves one key. B: d = {‘A’:1}; d[‘B’] = 4 leaves two. C: assigning zero to A does not delete it. D: deleting A makes a later unguarded lookup of A invalid unless it is reinserted. E: d[‘x’] is not the same as d[‘X’] for string keys. F: reading d[‘A’] does not change the value. G: len(d) counts pairs. H: if a stored value is the string ‘0037’, integer conversion can discard leading zeros.

Each answer follows from the specific operation, not a universal rule that every update adds a record. For marking, first check that the learner identified the intended key. Then check whether it existed and whether the line was a read, assignment or deletion. Finally ask for the resulting key count and the value that a later lookup would return. This sequence exposes the misconception more reliably than a single yes-or-no quiz.

A short learner assessment that tests transfer

Give the student a new mapping, such as {‘P1′:’ready’,’P2′:’waiting’}, and ask them to design four statements that produce the final state {‘P1′:’finished’,’P3′:’ready’}. One possible route is to replace P1, insert P3 and delete P2; there is no need to change every existing entry. Require the student to explain why the key P2 is absent rather than assigned the value ‘none’.

Then vary the task: require P2 to remain with value zero. That is a different desired final state, and deletion would now be incorrect. The exercise checks whether the student follows the specification, rather than relying on one memorised dictionary-editing recipe. A tutor can use a fresh synthetic mapping to confirm independent understanding.

Official source and related eduKateSG learning

Consult the 2027 SEC G3 Computing K349 syllabus and Python quick-reference guide, particularly 2.3.10. Related reading: Reference 363 — Python File Handling, Reference 364 — Python Strings, Reference 357 — Data Validation, the MOE V3.0 Library and the immutable Clementi teaching standard.

Reviewed 29 October 2026, Singapore. All records and code are fictional educational examples. The durable skill is to identify a key, decide whether a statement reads or changes the mapping, and report the current state without inventing missing information.

MOE V3.0 sequence navigation

Previous: Reference 364 — Python Strings · MOE V3.0 Library.