Modifying and Deleting Dictionary Items
Dictionaries are created empty using dict() or {} and store key-value pairs.
Try it: Dictionary Operations
How a Python dict behaves under everyday operations: d[k] raises KeyError for a missing key while get() returns None or a default, in tests keys (not values), assignment adds a new key at the end but updates an existing key in place, del and pop remove pairs, and iteration, keys(), values() and items() follow insertion order — with keys() a live view and list(d.keys()) a frozen copy.
How it works
- A dict maps unique keys to values; the pairs are kept in the order the keys were first inserted (Python 3.7+).
- d[k] returns the value for k or raises KeyError: 'k'; d.get(k) returns None and d.get(k, default) the default instead.
- k in d tests the keys only; testing a value needs v in d.values(); len(d) counts pairs.
- d[k] = v adds a new pair at the end when k is new, and replaces the value in place (same position) when k already exists; update() does this for each pair.
- del d[k] and d.pop(k) remove a pair (KeyError if missing; pop returns the value, or the default if one is given).
- keys(), values() and items() are views of the current dict; list(d.keys()) copies the keys at that moment. Filtering builds a NEW dict of the pairs that pass a test.
Default run (3 steps): d = {'apple': 3, 'fig': 7, 'pear': 5} — 3 key-value pairs, kept in insertion order. Choose an operation. Example: d.get('kiwi', 0). … The key is missing, so get returns the default 0 instead of raising KeyError. d is not changed.
Simplified: String keys (short lowercase words) and small int values, at most 8 pairs. The lab models what the operations do, not how CPython stores the dict (see the hashing lab for that). Every operation's result, error text, printed output and view contents match CPython 3.12 on 150 random operation sequences.
Loading the simulation…
From Empty to Populated
A dictionary begins as a container for key-value pairs. It can be created empty with dict() or with curly brackets, {}. Once the empty dictionary exists, square bracket assignment connects a key with a value. The dictionary then contains the pair that was assigned.
Creating the Container
The two empty-dictionary forms are dict() and {}. They use different notation, but both create an empty dictionary. This gives you two equivalent starting points before any key-value pairs are added.
| Syntax | Starting contents | Purpose |
|---|---|---|
| dict() | No key-value pairs | Create an empty dictionary |
| {} | No key-value pairs | Create an empty dictionary |
Both supported forms create an empty dictionary.
After creation, square bracket assignment uses the form dictionary[key] = value. The key appears inside square brackets, and the value appears to the right of the assignment symbol. For example, starting with an empty dictionary named settings, the assignment settings['theme'] = 'dark' adds the key-value pair theme and dark.
Tracing Several Assignments
Building a Small Dictionary
Start with an empty dictionary and add the pairs name and Mira, level and 3, and active and True.
- 1Start
Use either
dict()or {} to create the empty dictionary. - 2First assignment
Assign Mira to the key name. The dictionary now contains one key-value pair.
- 3Second assignment
Assign 3 to the key level. A second key-value pair is added.
- 4Third assignment
Assign True to the key active. A third key-value pair is added.
The resulting dictionary is {'name': 'Mira', 'level': 3, 'active': True}.
The example shows the state changing one assignment at a time. Each square bracket expression identifies the key whose value is being assigned. The resulting dictionary contains the key-value pairs that were added.
Insertion Order and Display
In Python 3.7 and later, dictionaries preserve insertion order. This means that items appear in the sequence in which they were added. If name is added first, level second, and active third, the dictionary's items appear in that same sequence.
A dictionary's output format shows key-value pairs inside curly brackets. Pairs are separated by commas, and each key is connected to its value with a colon. Because this displayed format is also valid input syntax, the shown structure can be used to create a dictionary with multiple items at once.
Reading Output as Input
Use the displayed dictionary {'city': 'Lima', 'visits': 2} as a model for creating a dictionary with two items at once.
- 1Identify the container
The curly brackets show that the structure is a dictionary.
- 2Identify each pair
city is connected to Lima, and visits is connected to 2.
- 3Preserve the written sequence
The city pair appears first and the visits pair appears second.
The same key-value structure serves as both dictionary output and valid input syntax.
Mistakes to Avoid
Common mistake Assuming dict() and {} create different kinds of empty containers.
What it looks likeTreating dict() as a non-dictionary because it uses parentheses.Why it failsThe source material identifies both forms as ways to create an empty dictionary.
Do this insteadRecognize dict() and {} as two supported syntaxes for the same starting purpose.
Common mistake Leaving out the square brackets when assigning a key.
What it looks likeWriting dictionary = 'value' instead of dictionary[key] = value.
Why it failsThe documented assignment form places the key inside square brackets before the assignment symbol.
Do this insteadUse dictionary[key] = value when adding a key-value pair.
Common mistake Expecting dictionary items to appear in an arbitrary order.
What it looks likeExpecting the last-added item to appear first in Python 3.7 or later.
Why it failsPython 3.7 and later preserve insertion order.
Do this insteadTrack the order in which pairs were added.
Common mistake Treating displayed dictionary output as unrelated formatting.
What it looks likeIgnoring the braces, colons, and commas when using a displayed dictionary as a model.
Why it failsThe dictionary output format is also valid input syntax.
Do this insteadRead the displayed form as a key-value structure that can create a dictionary with multiple items.
Common mistake Guessing deletion syntax from this lesson.
What it looks likeAdding an unprovided deletion command to a solution.
Why it failsThe supplied source material explains creation, assignment, order, and output/input format, but does not state a deletion operation.
Do this insteadUse only deletion syntax provided by a separate, authoritative lesson.
A dictionary starts empty. Describe the state after adding the pair language and Python, followed by the pair version and 3.7. Which pair appears first, and which two syntaxes could have been used to create the empty dictionary?
Hints
- Use square bracket assignment for each pair.
- Use insertion order to determine which pair appears first.
- The two empty-dictionary forms are
dict()and {}.
Key Takeaways
- 1
dict()and {} both create an empty dictionary. - 2Square bracket assignment uses dictionary[key] = value to add a key-value pair.
- 3Python 3.7 and later preserve the order in which dictionary items are inserted.
- 4A dictionary's displayed key-value format is also valid syntax for creating a dictionary with multiple items.
- 5The supplied source material does not define deletion syntax, so deletion should be learned from a separate documented operation.
At a glance
- Create an empty dictionary with
dict()or {}. - Add key-value pairs through square bracket assignment.
- Rely on insertion order in Python 3.7 and later when interpreting item order.
- Recognize dictionary output as valid input syntax.
- Do not assume deletion syntax that the source material has not specified.