Reading and Updating Values
Concepts covered: Dict Methods
Reading a value is the lookup from the previous section: square brackets with the key inside. That lookup fails when the key is missing, and adding a new key uses the same brackets on the left of an assignment.
Square brackets demand that the key exist
user = {"name": "Alice", "age": 28}
print(user["name"])
print(user["email"])The first print runs and shows Alice. The second asks for "email", which the dictionary doesn't hold, and Python stops the program with a KeyError. The last line of the traceback names the missing key in quotes, which is the first place to look when you see one. No print after line 3 would run.
.get() asks politely
user = {"name": "Alice", "age": 28}
print(user.get("name", "unknown"))
print(user.get("email", "no email on file"))
print(user.get("age", 0) + 1)Output:
Alice no email on file 29
user.get(key, default) looks the key up and returns its value when the key exists. When it does not, it returns the default you passed instead of stopping the program. The third line shows that the returned value is ordinary data: user.get("age", 0) is 28 here, so adding 1 prints 29. You can leave the default off and write user.get("email"), in which case a missing key returns a special value called None that stands for no value; a later lesson covers None, and until then passing a default keeps every result predictable.
.get never adds anything. After user.get("email", "none") the dictionary still has 2 pairs, the same as before the call.
- d[key]
- Returns the value when the key exists
- Stops the program with KeyError when it does not
- Use it when a missing key is a bug you want to notice
- d.get(key, default)
- Returns the value when the key exists
- Returns the default when it does not
- Use it when a missing key is a normal case, such as an optional setting
Writing with square brackets
Assignment through square brackets has the same shape as reading, with the lookup on the left of =. If the key is new, Python adds the pair; if the key already exists, Python replaces its value. Step through this program and watch the dictionary change:
user = {"name": "Alice", "age": 28}
print("Before:", user)
# Add a NEW key-value pair
user["email"] = "alice@email.com"
print("After adding email:", user)
# Update an EXISTING value
user["age"] = 29
print("After updating age:", user)Before: {'name': 'Alice', 'age': 28}
After adding email: {'name': 'Alice', 'age': 28, 'email': 'alice@email.com'}
After updating age: {'name': 'Alice', 'age': 29, 'email': 'alice@email.com'}
After line 5 the dictionary has 3 pairs, and after line 9 it still has 3: "age" kept its single pair while its value went from 28 to 29. Brackets behave differently for reads and writes, because reading a missing key crashes and writing to a missing key creates it. Every = with brackets on the left either adds or replaces, and never raises a KeyError.
user = {"name": "Alice", "tags": ["beta"]}
user["tags"].append("admin")
user["name"] = "Alicia"
print(user)Output:
{'name': 'Alicia', 'tags': ['beta', 'admin']}When a value is a list, user["tags"] hands you that list, and .append changes it in place, so the dictionary sees the new tag without any assignment back. Replacing "name" works as before. Reading and writing combine in 1 line: stock["apple"] = stock["apple"] + 2 adds 2 to the old count read on the right and stores the sum under the same key.
Practice
What does the last line print?
stock = {"apple": 3}
stock["pear"] = 5
stock["apple"] = stock["apple"] + 2
print(stock.get("plum", 0), stock["apple"], len(stock))- 0 3 2
- A traceback, because "plum" was never added
- 0 5 3
- 0 5 2
One more worked case before you write your own. An update line runs its right side first: Python evaluates the right side, lookup and arithmetic included, and only then stores the result under the key on the left. A new key needs no such read, because there is nothing to read yet.
temps = {"mon": 18, "tue": 21}
temps["wed"] = 19
temps["mon"] = temps["mon"] + 4
print(temps)
print(temps.get("thu", 0))
print(len(temps))Output:
{'mon': 22, 'tue': 21, 'wed': 19}
0
3"wed" joins at the end through a plain assignment, and "mon" keeps its first position while its value goes from 18 to 22. The .get for "thu" returns 0 and leaves the dictionary at 3 pairs. Writing temps["thu"] + 4 on the right of an assignment would have stopped the program with a KeyError, since a missing key can't be read with brackets.
About this lesson
This section is part of the Dictionaries: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.