Dictionary Methods
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…
A Dictionary Before It Has Data
A dictionary begins as a container for key-value pairs. You can create that container empty, then add pairs one at a time. Python provides two forms for creating an empty dictionary: dict() and {}.
{}
{}Adding the First Pair
Square bracket assignment adds a key-value pair to a dictionary. The general form is dictionary[key] = value. The expression inside the brackets identifies the key, and the expression after the equals sign supplies the associated value.
profile = {}
profile["name"] = "Mira"
profile["level"] = 3
print(profile)- 1profile = {} creates an empty dictionary.
- 2profile["name"] = "Mira" adds the key name with the value Mira.
- 3profile["level"] = 3 adds the key level with the value 3.
- 4
print(profile)displays both key-value pairs in their insertion order.
{'name': 'Mira', 'level': 3}Reading the Dictionary State
A dictionary is organized as key-value pairs. In the displayed form, each key is followed by its associated value, and multiple pairs appear together inside curly brackets. This makes the displayed dictionary easy to read as a representation of the data that was entered.
Building a Dictionary Step by Step
Create a dictionary containing a color and a quantity by starting with an empty dictionary.
- 1Start empty
Use {} to create a dictionary with no key-value pairs.
- 2Add the color
Use inventory["color"] = "blue" to add the key color and its value blue.
- 3Add the quantity
Use inventory["quantity"] = 4 to add the key quantity and its value 4.
- 4Inspect the result
The dictionary display contains both pairs inside curly brackets.
{'color': 'blue', 'quantity': 4}
Insertion Order in Python 3.7 and Later
In Python 3.7 and later, dictionaries preserve insertion order. That means dictionary items appear in the sequence in which you added them. If one pair is added first and another pair is added second, the displayed dictionary keeps that order.
{'first': 'open', 'second': 'save', 'third': 'close'}From Input Syntax to Display
The format Python displays for a dictionary is also valid input syntax for creating a dictionary with multiple items at once. Curly brackets surround the pairs, and each pair is written in key-value form. This gives you two connected ways to understand dictionaries: the displayed form shows the structure, and the same structure can be entered as dictionary input.
settings = {}
settings["mode"] = "quiet"
settings["retries"] = 2The dictionary is built through separate square bracket assignments.
settings = {"mode": "quiet", "retries": 2}The same key-value pairs are written together in dictionary format.
Mistakes with Dictionary Construction
Common mistake Using parentheses as though they were the empty-dictionary syntax.
What it looks likeitems = ()Why it failsThe two empty-dictionary forms covered here are
dict()and {}.Do this insteadUse items = dict() or items = {}.Common mistake Leaving out the square brackets when adding a pair.
What it looks likeprofile = {} profile "name" = "Mira"Why it failsA dictionary key is specified inside square brackets in the assignment form.
Do this insteadWrite profile["name"] = "Mira".Common mistake Expecting dictionary pairs to appear in a different order from the order of insertion in Python 3.7 and later.
What it looks likedata["second"] = 2 data["first"] = 1Why it failsPython 3.7 and later preserve insertion order, so second appears before first in the displayed sequence.
Do this insteadRead the displayed order as the order in which the pairs were added.
Common mistake Treating the displayed dictionary format as unrelated to input syntax.
What it looks likedata = {"first": 1, "second": 2}Why it failsThe dictionary representation shown by Python is also valid input syntax for creating multiple pairs at once.
Do this insteadUse the displayed key-value structure as a model for writing a dictionary literal.
Practice the State Changes
Create an empty dictionary using curly brackets. Add the pair "language": "Python", then add the pair "version": 3.7. Write the dictionary you expect Python to display and preserve in order.
Hints
- Begin with settings = {}.
- Use square bracket assignment for each pair.
- Place the pair added first before the pair added second in the displayed dictionary.
What do you think happens?
What will Python display after these assignments?
record = {}record["topic"] = "dictionaries"record["length"] = 1
Reveal answer
{"topic": "dictionaries", "length": 1}
In Python 3.7 and later, dictionary items appear in the sequence in which they were added. topic was added before length.
Dictionary Construction Checklist
- 1Create an empty dictionary with
dict()or {}. - 2Add a key-value pair with dictionary[key] = value.
- 3In Python 3.7 and later, dictionary items appear in insertion order.
- 4A dictionary's displayed key-value format is also valid input syntax for creating multiple pairs at once.
Key Takeaways
dict()and {} both create empty dictionaries.- Square bracket assignment adds key-value pairs.
- Python 3.7 and later preserve the order in which dictionary pairs are inserted.
- The dictionary format Python displays can also be used as input syntax for multiple key-value pairs.