0
0
Pythonprogramming~15 mins

Adding and updating key-value pairs in Python - Deep Dive

Choose your learning style9 modes available
Overview - Adding and updating key-value pairs
What is it?
Adding and updating key-value pairs means putting new information into a dictionary or changing existing information. A dictionary is like a labeled box where each label (key) points to a value. When you add a new key and value, you create a new label and put something inside. When you update, you change what is inside an existing label.
Why it matters
Without the ability to add or update key-value pairs, dictionaries would be static and useless for most programs. We need to store and change information dynamically, like keeping track of scores in a game or user settings. This concept lets programs remember and modify data easily, making them flexible and powerful.
Where it fits
Before learning this, you should understand what dictionaries are and how to create them. After this, you can learn about dictionary methods, looping through dictionaries, and more complex data structures like nested dictionaries.
Mental Model
Core Idea
A dictionary is a collection of labeled boxes where you can add new boxes or change what’s inside existing boxes by using their labels.
Think of it like...
Imagine a filing cabinet with folders labeled by names. Adding a key-value pair is like adding a new folder with a label and some papers inside. Updating is like replacing the papers inside an existing folder without changing the label.
Dictionary
┌───────────────┐
│ Key  │ Value  │
├──────┼────────┤
│ 'a'  │ 1      │  ← Add new key 'a' with value 1
│ 'b'  │ 2      │  ← Update key 'b' to new value 2
└──────┴────────┘
Build-Up - 7 Steps
1
FoundationWhat is a dictionary in Python
🤔
Concept: Introduce the dictionary as a data structure that stores key-value pairs.
A dictionary in Python looks like this: my_dict = {'name': 'Alice', 'age': 25} Here, 'name' and 'age' are keys, and 'Alice' and 25 are their values. You can get a value by using its key, like my_dict['name'] which gives 'Alice'.
Result
You can store and access data by labels (keys) instead of positions.
Understanding dictionaries as labeled containers is the base for adding or updating data inside them.
2
FoundationAccessing and understanding keys and values
🤔
Concept: Learn how to read values from a dictionary using keys.
Using my_dict = {'color': 'blue', 'size': 'medium'}, you get the value by writing my_dict['color'], which returns 'blue'. If you try a key that doesn't exist, Python gives an error.
Result
You can retrieve stored information by its key.
Knowing how to access values prepares you to add or update them correctly.
3
IntermediateAdding new key-value pairs
🤔Before reading on: Do you think adding a new key-value pair changes the original dictionary or creates a new one? Commit to your answer.
Concept: Learn how to add a new key and value to an existing dictionary.
To add a new key-value pair, assign a value to a new key: my_dict = {'fruit': 'apple'} my_dict['color'] = 'red' Now my_dict is {'fruit': 'apple', 'color': 'red'}.
Result
The dictionary now contains the new key and value.
Knowing that dictionaries are mutable means you can change them directly by adding new keys.
4
IntermediateUpdating existing key-value pairs
🤔Before reading on: When you update a key’s value, does Python add a new key or replace the old value? Commit to your answer.
Concept: Learn how to change the value of an existing key in a dictionary.
If a key already exists, assigning a new value to it replaces the old one: my_dict = {'fruit': 'apple'} my_dict['fruit'] = 'banana' Now my_dict is {'fruit': 'banana'}.
Result
The value for the key is updated without adding a new key.
Understanding that keys are unique and values can be changed helps avoid duplicate keys and confusion.
5
IntermediateUsing the update() method
🤔Before reading on: Does update() add only new keys, only update existing keys, or both? Commit to your answer.
Concept: Learn how to add or update multiple key-value pairs at once using update().
The update() method can add new keys or change existing ones: my_dict = {'a': 1, 'b': 2} my_dict.update({'b': 3, 'c': 4}) Now my_dict is {'a': 1, 'b': 3, 'c': 4}.
Result
The dictionary has updated 'b' and added 'c' in one step.
Knowing update() lets you efficiently change many keys at once, which is useful in real programs.
6
AdvancedHandling missing keys safely
🤔Before reading on: What happens if you try to update a key that doesn’t exist? Does it cause an error or add the key? Commit to your answer.
Concept: Learn how adding or updating keys works even if the key is missing, and how to avoid errors when accessing keys.
Assigning a value to a missing key adds it without error: my_dict = {} my_dict['new'] = 10 # adds key 'new' But accessing a missing key like my_dict['missing'] causes an error. Use my_dict.get('missing') to safely get None instead.
Result
You can add keys anytime, but must be careful when reading keys that might not exist.
Understanding this prevents crashes and helps write safer code when working with dictionaries.
7
ExpertMutable values and updating nested dictionaries
🤔Before reading on: If a dictionary value is a list, does updating the list inside the dictionary change the dictionary itself? Commit to your answer.
Concept: Learn how updating mutable values inside dictionaries affects the dictionary and how to update nested dictionaries.
If a dictionary value is mutable like a list, changing the list changes the dictionary content: my_dict = {'numbers': [1, 2]} my_dict['numbers'].append(3) Now my_dict is {'numbers': [1, 2, 3]}. For nested dictionaries: my_dict = {'outer': {'inner': 1}} my_dict['outer']['inner'] = 2 Updates the inner value without replacing the outer dictionary.
Result
You can update complex data inside dictionaries without replacing whole entries.
Knowing how mutability works inside dictionaries helps avoid bugs and write efficient updates.
Under the Hood
Python dictionaries use a hash table internally. When you add or update a key-value pair, Python computes a hash from the key to find where to store the value quickly. If the key exists, it replaces the value at that spot; if not, it finds an empty slot to add the new pair. This makes adding and updating very fast, even for large dictionaries.
Why designed this way?
Dictionaries were designed for fast lookup and modification. Using hashing allows constant time operations on average. Alternatives like lists would be slower for key-based access. The design balances speed and memory use, making dictionaries a core Python data structure.
Dictionary Internal Structure
┌───────────────┐
│ Key Hash      │
├───────────────┤
│ Index in Table│
├───────────────┤
│ Value Stored  │
└───────────────┘

Add/Update Process:
Key → hash(key) → index → store or replace value
Myth Busters - 4 Common Misconceptions
Quick: Does assigning a value to an existing key add a new key or update the old one? Commit to your answer.
Common Belief:Assigning a value to a key always adds a new key-value pair.
Tap to reveal reality
Reality:If the key exists, the value is updated; no new key is added.
Why it matters:Thinking it adds a new key can cause confusion and bugs, like unexpected dictionary sizes or duplicate keys.
Quick: Does the update() method only add new keys or also update existing keys? Commit to your answer.
Common Belief:update() only adds new keys and never changes existing ones.
Tap to reveal reality
Reality:update() adds new keys and updates values of existing keys.
Why it matters:Misunderstanding this can lead to accidental overwriting of data.
Quick: If a dictionary value is a list, does changing the list inside the dictionary change the dictionary? Commit to your answer.
Common Belief:Changing a list inside a dictionary does not affect the dictionary itself.
Tap to reveal reality
Reality:Since the list is stored by reference, modifying it changes the dictionary’s content.
Why it matters:Ignoring this can cause unexpected side effects and bugs when modifying nested data.
Quick: Does accessing a missing key in a dictionary return None or cause an error? Commit to your answer.
Common Belief:Accessing a missing key returns None.
Tap to reveal reality
Reality:Accessing a missing key raises a KeyError exception.
Why it matters:Assuming it returns None can cause crashes if not handled properly.
Expert Zone
1
Updating a key’s value does not change the dictionary’s order in Python 3.7+ because dictionaries preserve insertion order.
2
Using update() with another dictionary or iterable of pairs is more efficient than multiple single assignments.
3
Mutable values inside dictionaries can lead to subtle bugs if shared across different keys or dictionaries.
When NOT to use
Avoid using direct assignment or update() when you need to keep the original dictionary unchanged; instead, create a copy and modify that. For immutable mappings, use types like MappingProxyType. For very large datasets requiring fast concurrent updates, consider specialized data structures or databases.
Production Patterns
In real-world code, adding and updating key-value pairs is common in configuration management, caching, and data aggregation. Patterns include using update() to merge dictionaries, safely checking keys before updating, and handling nested dictionaries with helper functions or libraries like collections.defaultdict.
Connections
Hash Tables
Dictionaries are an implementation of hash tables.
Understanding hash tables explains why adding and updating keys is fast and how collisions are handled.
Mutable vs Immutable Data
Updating dictionary values depends on whether values are mutable or immutable.
Knowing data mutability helps predict how changes inside dictionaries affect program state.
Database Key-Value Stores
Dictionaries in Python are like in-memory key-value stores used in databases.
Learning dictionary updates helps understand how databases store and update records efficiently.
Common Pitfalls
#1Trying to access a key that does not exist causes a program crash.
Wrong approach:my_dict = {'a': 1} print(my_dict['b']) # KeyError
Correct approach:my_dict = {'a': 1} print(my_dict.get('b')) # None, no error
Root cause:Not knowing that accessing missing keys raises an error instead of returning None.
#2Assuming update() only adds new keys and does not overwrite existing ones.
Wrong approach:my_dict = {'x': 5} my_dict.update({'x': 10}) # Expect x to be 5, but it becomes 10
Correct approach:my_dict = {'x': 5} my_dict.update({'x': 10}) # x is updated to 10 as expected
Root cause:Misunderstanding the behavior of the update() method.
#3Modifying a mutable value inside a dictionary without realizing it changes the dictionary.
Wrong approach:my_dict = {'list': [1, 2]} my_dict['list'].append(3) # Unexpectedly changes my_dict
Correct approach:my_dict = {'list': [1, 2]} new_list = my_dict['list'][:] # copy list new_list.append(3) # my_dict unchanged
Root cause:Not understanding that mutable objects are referenced inside dictionaries.
Key Takeaways
Dictionaries store data as key-value pairs where keys are unique labels and values hold the data.
You can add new key-value pairs by assigning a value to a new key, and update existing ones by assigning a new value to an existing key.
The update() method lets you add or change multiple key-value pairs at once efficiently.
Accessing a missing key causes an error, so use safe methods like get() to avoid crashes.
Mutable values inside dictionaries can be changed without replacing the whole entry, which can lead to subtle bugs if not handled carefully.