Dictionaries: model lookup, not position
Use keys to turn repeated searching into direct lookup.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 13 minutes; optional deep dive: 10 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Create and update mappings
- Handle absent keys
- Build a frequency map
Keys express identity
A dictionary connects each key to a value. Ask for the key you know to find the value you need, instead of remembering an item's position.
Understand first
Use a dictionary for a name's arrival count, an ID's customer record, or a setting's value. A list answers which item is at a position; a dictionary answers which value belongs to a key.
Words you will see
- Key / value
- The label you look up and the information stored under it.
- Mapping
- A collection of key-to-value connections.
- Missing key
- A key that has no entry. This is different from an entry whose value is zero or None.
Read the notation before the counter
In {"Ada": 2}, the braces build a dictionary, the colon connects key "Ada" to value 2, and commas separate more entries. {} is an empty dictionary. Keys are unique: assigning another value under "Ada" updates that entry rather than adding a second Ada key.
counts["Ada"] reads an existing entry and raises KeyError if it is absent. counts.get("Ada", 0) reads with an explicit default of 0; it does not insert a missing entry. Choose that default because zero is the right starting count here, not because all missing information should mean zero.
Build the count one arrival at a time
The loop visits Ada, Lin, then Ada. Start with no entries. For the first Ada, get returns 0; add 1 and assign the value 1 under Ada. Lin also starts at 0. For the second Ada, get reads the existing 1; adding 1 makes it 2.
The assignment on the left is what creates or updates the entry. A get call alone does not do that. After the loop, there are two keys representing three arrivals. Asking for Sam gives 0 without changing the dictionary. A default expression is evaluated before get is called; get is not a lazy computation API.
Choose the information you want to keep
A counter keeps each name's total but loses the separate arrival history. Keep a list as well if timestamps or individual arrival order matter. Keys must support stable lookup; strings work well. We explain the formal word hashable in optional depth.
The counter takes one pass over the arrivals and keeps one entry per distinct name. In ordinary hash-table behavior this is linear total work on average, with storage growing with distinct names. Reading a known key is not a scan through a list, but it is not an unconditional worst-case constant-time promise.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
counts = {}Start with no names or counts.
for name in ["Ada", "Lin", "Ada"]:Read three arrivals in order, including the repeated name.
counts[name] = counts.get(name, 0) + 1Read the old count or zero, add one, and store the result under the same name.
print(counts.get("Sam", 0))Display 0. Sam is still not a key afterwards.
A dict maps unique hashable keys to values. Use it for product IDs, configuration, cached results and counters. d[key] raises KeyError when absent; d.get(key, default) returns a fallback without inserting it.
A key is not a position.
This is a conceptual string-key model, not a hash-table memory layout or a trace of your edited Python.
teamaps to2breadmaps to1
Two keys, each connected to one quantity.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add another Lin arrival.
Try: Add "Lin" to the input list, then run again.
Lin becomes 2; Ada stays 2.
Prove that reading Sam did not insert it.
Try: Add print("Sam" in counts).
It prints False even though get returned 0.
Before you move on
For arrivals ["Lin", "Lin", "Ada"], what are the final counts? Does counts.get("Sam", 0) add Sam?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The result is {"Lin": 2, "Ada": 1}. Reading Sam with get gives 0 but leaves the keys unchanged. Only the assignment in the loop creates or updates entries.
Iterate intent
A dictionary loop reads keys unless you ask for values or key/value pairs. Its insertion order is useful information, but it is not sorted order.
Understand first
When printing a receipt you need both product and quantity. When checking whether a product exists you need keys, not a search through quantities.
Words you will see
- items()
- A view of key/value pairs that can be unpacked in a loop.
- View
- A live connection to the dictionary's contents, not a frozen copy.
- Insertion order
- The order in which keys were first added.
Ask for the right part
for product in orders reads "tea", then "bread". for quantity in orders.values() reads 2, then 1. for product, quantity in orders.items() unpacks each two-part pair into meaningful names.
"tea" in orders tests keys. 2 in orders does not test whether 2 is a quantity; 2 in orders.values() does. The latter can inspect many values, so do not assume it has the same lookup cost as testing a key.
Order and snapshots are separate decisions
Updating an existing key leaves its position unchanged. Deleting a key and inserting it again puts it at the end. Python guarantees insertion order, but it does not arrange tea and bread alphabetically for you. Use sorted(orders) when you explicitly need sorted keys.
The values and items objects are live views. list(orders.items()) records the current pairs in a new list, but nested mutable values are still shared. Do not add or delete keys while walking the same dictionary: its size may change and raise RuntimeError. Build a result separately or deliberately iterate a snapshot.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
print(list(orders))Display the inserted keys, not their quantities.
print(list(orders.values()))Display the values in corresponding insertion order.
print(list(orders.items()))Display two-entry tuples pairing each key with its value.
orders["tea"] = 4Update tea in its existing position; the last key list remains tea, bread.
Iterating a dict yields keys. Use .items() for key/value pairs and .values() for values. Membership tests keys, not values. Modern Python preserves insertion order; it does not automatically sort keys.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Read both pieces in a loop.
Try: Add: for product, quantity in orders.items(): print(product, quantity)
Each pair supplies a product name and its current quantity.
Compare update with reinsertion.
Try: Add del orders["tea"], then orders["tea"] = 4 on the next line, then print(list(orders)).
Tea moves to the end only after deletion and reinsertion.
Before you move on
If you delete tea and insert it again after bread, what is the key order? Would changing only its quantity have the same effect?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The order becomes bread, tea. Reinsertion is a new insertion. Updating the quantity of a key that still exists does not move it.
Update without losing the model
Assignment updates one key, update merges entries into the same dictionary, and pop removes a key while returning its value. Decide explicitly what missing data means.
Understand first
A stock record changes over time. Choosing an operation by its promise prevents lost values, accidental mutation and missing-data bugs.
Words you will see
- update
- Merge another mapping or pairs into this dictionary; later supplied values win.
- pop
- Remove a key and return its value; an optional default handles a missing key.
- setdefault
- Return an existing value or insert and return a supplied default when the key is absent.
Separate modifying an object from making a new one
stock["tea"] = 3 replaces the old tea quantity. stock.update({"milk": 1}) adds milk. update changes the existing dictionary and returns None, so stock = stock.update(...) would make stock name None.
For flat mappings, left | right builds a new dictionary and lets right win on equal keys. left |= right edits left. This is replacement, not addition: merging two counters with update does not sum their shared counts. Our guided exercise below asks you to implement addition explicitly.
Choose a missing-key policy and a removal rule
stock.pop("coffee", 0) returns 0 if coffee is absent. Without the default it raises KeyError. del stock["coffee"] also raises KeyError when absent. popitem() removes the last inserted remaining pair and fails on an empty dictionary. clear() empties the existing mapping.
setdefault is useful when a missing key should acquire a value, such as a new list for grouping. get merely reads. Choose an error when a missing record violates the contract; choose a default only when it represents a valid case. Do not silently turn unknown inventory into a known quantity.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
stock["tea"] = 3Replace tea's value in place.
stock.update({"milk": 1})Add milk to the same mapping.
print(stock.pop("coffee", 0))No coffee is removed; display the agreed missing-value default.
print(stock.popitem())Remove and return the most recent pair, ('milk', 1).
Assigning an existing key replaces its value without creating a duplicate key. pop removes a key and can accept a default. Be explicit whether absent data means zero, unknown, or an error.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe a missing-key failure.
Try: Remove the default 0 from pop("coffee", 0).
The run shows KeyError rather than pretending the missing key was removed.
Keep the original while merging.
Try: Compare stock | {"milk": 2} with stock.update({"milk": 2}) and print stock after each.
The union expression creates a new mapping; update modifies stock.
Before you move on
If left is {"Ada": 2} and right is {"Ada": 3}, does left.update(right) produce 5? Does it return left?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It changes left's Ada value to 3 and returns None. To combine counts, read each existing count and add the supplied count deliberately.
Where this idea earns its place
A dict models association by key, not by numeric position. Product IDs, configuration names and frequency counts are natural uses. Choose the key according to domain identity; a display name may not uniquely identify a customer. Decide what absence means before using get with a convenient default, since zero, unknown and invalid are different states.
Follow the mechanism step by step
Hashing narrows where a key may be stored, then equality distinguishes candidates. Equal keys must have equal hashes, and the key's hash must stay stable while stored. Modern Python preserves insertion order, but that order does not imply numeric sorting or a universal serialization order across differently constructed mappings.
Work through a concrete application
For a frequency table, read the current count or its documented zero starting value and assign the incremented result. Iterate items when both key and value are needed. For optional configuration, use a unique sentinel when an absent key differs from a key explicitly mapped to None. Validate external record shapes before assuming .get exists.
Failure cases and misleading shortcuts
Membership checks keys, not values. A shallow dict copy shares nested lists and dicts. Mutating size while iterating a live view can fail or create hard-to-follow behaviour. A broad default can also hide a misspelled required key, so brackets and an explicit error may be preferable for mandatory fields.
Cost, ownership and alternatives
Lookup and insertion are expected O(1) under bounded hash/equality costs, with pathological cases degrading. Grouping k distinct keys consumes O(k) entries plus stored values. For a stream with unbounded cardinality, an input iterator alone does not bound aggregation memory; you may need partitioning or external storage.
Verify the contract
Test absent keys, present-but-None, equal keys, repeated updates and nested ownership. When order is part of a public report, assert it deliberately rather than relying only on dict equality. For user-controlled data, bound key length and distinct-key count and keep validation errors separate from a valid empty mapping.
Transfer question: A configuration key is optional but None is meaningful. Why is get(key) insufficient?
Both absence and a present None return None with that call. Supply a unique sentinel, compare by identity, and handle absence separately. Do not use a normal domain value as the sentinel when that value could legitimately appear in the mapping.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Count letters
Count each letter in banana using a dict.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: count every arrival
Return a frequency map without editing the input list.
The contract
- Input is a list of name strings; names are case-sensitive.
- Return a dictionary with one entry per distinct name and its occurrence count.
- Keep keys in first-arrival order; preserve the input; empty input gives a fresh empty dictionary.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- repeated names
assert count_names(["Ada", "Lin", "Ada"]) == {"Ada": 2, "Lin": 1}, "Count every arrival" - empty input
assert count_names([]) == {}, "Empty input has no names" - case-sensitive
assert count_names(["Ada", "ada"]) == {"Ada": 1, "ada": 1}, "Do not merge different strings" - first arrival order
assert list(count_names(["Lin", "Ada", "Lin"])) == ["Lin", "Ada"], "Keep first-arrival key order"
- input preserved
names = ["Lin", "Ada"] assert count_names(names) == {"Lin": 1, "Ada": 1} and names == ["Lin", "Ada"], "Do not edit the arrivals" - independent empty results
first = count_names([]) second = count_names([]) assert first is not second, "Each call needs its own result"
Why is get alone not enough to build the map?
get reads; assignment stores the increment. For n arrivals and u distinct names, the loop uses average O(n) time and O(u) output storage with bounded-cost hashing/equality.
Guided: combine two counters
Shared names need added totals, not a last-writer replacement.
The contract
- Inputs are dictionaries from name strings to nonnegative integer counts.
- Return a fresh dictionary with summed counts for shared keys and copied counts for other keys.
- Preserve both inputs; retain left's key order, followed by new right-only keys in right's order.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- shared keys
assert merge_counts({"Ada": 2}, {"Ada": 3}) == {"Ada": 5}, "Sum shared counts" - distinct keys
assert merge_counts({"Ada": 2}, {"Lin": 1}) == {"Ada": 2, "Lin": 1}, "Keep both mappings" - zero counts
assert merge_counts({"Ada": 0}, {"Ada": 0}) == {"Ada": 0}, "Zero is a valid count" - empty results
assert merge_counts({}, {}) == {}, "Empty inputs give an empty mapping" - key order
assert list(merge_counts({"Lin": 1, "Ada": 2}, {"Sam": 3, "Lin": 4})) == ["Lin", "Ada", "Sam"], "Preserve existing key positions" - ownership
left = {"Ada": 2} right = {"Ada": 3} result = merge_counts(left, right) assert isinstance(result, dict) and result == {"Ada": 5} and left == {"Ada": 2} and right == {"Ada": 3} and result is not left and result is not right, "Return the sum in a new dictionary and preserve both callers"
Why is shallow copying enough here?
The values are immutable integers and updates replace outer values. For a left mapping of l keys and right mapping of r keys, average time is O(l + r); output storage grows with the union of keys. Nested mutable values would need another policy.
Transfer: remember the first arrival
Change the rule: store each name's first zero-based position, not its count or last position.
The contract
- Input is a list of name strings.
- Return each distinct name mapped to the index of its first occurrence.
- Keep first-arrival key order; do not change the input; empty input returns a fresh empty mapping.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- first not last
assert first_positions(["Ada", "Lin", "Ada"]) == {"Ada": 0, "Lin": 1}, "Keep the first position" - repeated first name
assert first_positions(["Lin", "Lin"]) == {"Lin": 0}, "Position zero is valid" - empty
assert first_positions([]) == {}, "No arrivals means no positions" - case
assert first_positions(["Ada", "ada"]) == {"Ada": 0, "ada": 1}, "Names are case-sensitive" - order
assert list(first_positions(["Sam", "Ada", "Sam"])) == ["Sam", "Ada"], "Keep first-arrival order"
- input unchanged
names = ["Lin", "Ada", "Lin"] assert first_positions(names) == {"Lin": 0, "Ada": 1} and names == ["Lin", "Ada", "Lin"], "Preserve input"
Why does a counter implementation fail this requirement?
Counts and positions are different information. Membership prevents overwriting the first position, including zero. For n arrivals and u distinct names, expected time is O(n) and output space O(u), under ordinary hash-table assumptions.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneHash table, with conditions
A dictionary uses a key's hash to narrow a lookup, then equality to identify the matching key. Fast average lookup depends on a valid, stable key contract.
Understand first
Understand why a list cannot be a key, why two unequal keys may share a hash, and why average O(1) is not a universal performance guarantee.
Words you will see
- Hash
- An integer used to help locate a candidate entry; it is not a unique identifier.
- Hashable
- Has a hash that stays stable during its lifetime and equality consistent with that hash.
- Collision
- Different keys sharing a hash or competing for lookup positions.
Hash first; equality still matters
Equal keys must have equal hashes. Equal hashes do not prove equal keys, so a dictionary must still distinguish candidates by equality. CPython uses a hash-table implementation with space reserved for growth; a diagram of key/value pairs is not its physical memory layout.
Strings, integers and tuples of hashable values are useful keys. Lists and dictionaries are unhashable because their changing contents are not a suitable value-key contract. Custom classes can implement hashing, but changing a field that participates in a stored key's hash/equality can break lookup expectations.
Read the performance promise with its assumptions
For n entries, lookup, assignment and deletion are average O(1) when hashes and equality checks are well behaved. Collisions and expensive key operations can make a lookup worse; a pathological case can approach O(n). Building or copying all n entries takes O(n) work and storage under ordinary bounded-cost assumptions.
True and 1 compare equal and have equal hashes. They therefore represent one dictionary key, even though their types differ. This is equality-based identity in a mapping, not a general rule that the dictionary preserves every differently written literal as a separate entry.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
people = {("EU", 7): "Ada"}The two-part tuple is hashable because both of its items are hashable.
people[["EU", 7]] = "Lin"A list is unhashable; the matching TypeError handler explains the failed insertion.
numbers = {1: "integer", True: "boolean"}The later equal key replaces the value for the same entry.
print(len(numbers))One key remains; reading numbers[1] gives boolean.
Lookups and updates are expected O(1) average, but pathological collisions can cost O(n). Hashable keys need a stable hash and equality contract. Lists are unhashable; tuples of hashable values can work.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try a tuple with an unhashable item.
Try: Replace the list key with ("EU", [7]).
The outer tuple does not make the inner list hashable.
Compare two distinct integer keys.
Try: Replace True with 2.
The dictionary now has two entries because 1 and 2 are unequal.
Before you move on
Can two unequal keys have the same hash? Can a tuple containing a list be a dictionary key?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Unequal keys can share a hash; equality separates them. A tuple containing a list is unhashable because the tuple's hash depends on all its items being hashable.
Missing versus present-but-None
An absent key, a present None value and a shared nested object are three different situations. A shallow dictionary copy separates entries, not the objects they reference.
Understand first
APIs and configuration often distinguish not provided from explicitly empty. Copies used for edits must protect exactly the levels the caller expects to keep unchanged.
Words you will see
- Sentinel
- A unique marker used to represent a special state such as missing.
- Identity: is
- Whether two names refer to the same object, not just equal values.
- Shallow copy
- A new outer mapping that initially shares its key and value objects.
Do not collapse different states into one default
record.get("nickname") and record.get("other") both give None here, but one key exists and the other does not. Use "nickname" in record if you only need presence. Supply a unique object() marker as the default for get if you also want the retrieved value.
Compare that marker with is, because you care about the one sentinel object, not equality with an arbitrary user value. Do not use if value to detect absence: valid values such as 0, False, an empty string and None can all be false in a condition.
Copy the right level, not just the convenient one
shallow = record.copy() creates independent outer entries. shallow["nickname"] = "A" would not replace the original nickname. But both tags entries still lead to the same list, so appending through either mapping changes that shared list.
The dictionary unpacking expression {**record, ...} merges entries into a new mapping; the later explicit tags entry replaces the earlier one. Copying that tag list protects it for this flat-string example. Deeper mutable values need a deliberate ownership policy; a shallow copy is not recursive isolation.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
missing = object()Create a marker that no existing user value already names.
print(record.get("nickname", missing) is missing)Print False: the key exists, even though its value is None.
print(record.get("other", missing) is missing)Print True: no such key exists.
shallow["tags"].append("vip")Edit the list shared by both dictionaries.
isolated = {**record, "tags": record["tags"].copy()}Create new outer entries and a new tags list for the level that must change independently.
get returning None cannot distinguish an absent key from a key explicitly mapped to None. Use a unique sentinel when that distinction matters. A dict copy is shallow, just like a list copy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Separate tags in the first copy too.
Try: Use shallow = {**record, "tags": record["tags"].copy()}.
Appending vip no longer changes record's tags.
Test a false-but-present value.
Try: Add record["limit"] = 0, then compare "limit" in record with bool(record.get("limit")).
Presence is True while the value's truthiness is False.
Before you move on
For {"limit": 0, "label": None}, which keys are present? Would if record.get(key) correctly test presence?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Both keys are present. Both values are false in a condition, so that test would incorrectly treat them as missing. Use membership or a unique sentinel, according to the contract.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.