Python Dictionary Append: How to Add Items to Dictionary
What is a dictionary in Python?
A dictionary in Python is a built-in data structure that stores information as key-value pairs, allowing for fast and flexible data access. Dictionaries are widely used for mapping data, storing configurations, and managing structured inputs dynamically. Some of the key features of Python dictionaries are:
- Store data as key-value pairs
- Keys must be unique and immutable
- Values can be of any data type
- Mutable and can be modified after creation
- Unordered before Python 3.7, insertion-ordered from Python 3.7+
To add new items to a dictionary, Python provides several methods tailored to different needs. Here’s a quick overview:
Single item:
dict[key] = value
Multiple items:
dict.update({'key': 'value'})
Conditional add:
dict.setdefault('key', 'default')
Merge dictionaries:
dict1 | dict2
(Python 3.9+)Bulk add: Use loops for dynamic insertion
Let’s explore each method in detail with examples.
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today. Try it for freeAdding items to the dictionary using square brackets ([]
)
The most direct and commonly used way to add or update items in a Python dictionary is by using square brackets ([]
) with the assignment operator (=
). This method allows you to assign a value to a new key or update the value of an existing key. This approach is basic, readable, and works across all Python versions.
Syntax for the []
brackets is:
dictionary[key] = value
Here:
- If the key does not exist, it adds a new key-value pair.
- If the key already exists, it updates the existing value.
Example:
student = {"name": "Aria", "age": 12}# Add a new key-value pairstudent["grade"] = "7th"# Update an existing keystudent["age"] = 13print(student)
This code produces the following output:
{'name': 'Aria', 'age': 13, 'grade': '7th'}
Using []
has several advantages, as follows:
- The most straightforward and beginner-friendly method
- Works for both inserting new keys and updating existing ones
- No imports or version-specific syntax is required
- Efficient for adding a single item at a time
But what if we need to add multiple key-value pairs? Can we use []
? In a case like this, the update()
method can be more convenient.
How to add multiple items to a dictionary using update()
The update()
method in Python is used to add multiple key-value pairs to an existing dictionary in a single step. It can also be used to update the values of existing keys efficiently. This method is beneficial when you merge dictionaries or perform batch insertions.
Syntax of the update()
method is:
dictionary.update([other])
Parameters:
other
can be another dictionary or an iterable of key-value pairs, like a list of tuples.
Example:
profile = {"name": "Liam", "country": "USA"}# Add multiple key-value pairs using a dictionaryprofile.update({"age": 30, "profession": "Engineer"})# Or using a list of tuplesprofile.update([("language", "Python"), ("experience", "5 years")])print(profile)
This code produces the following output:
{'name': 'Liam', 'country': 'USA', 'age': 30, 'profession': 'Engineer', 'language': 'Python', 'experience': '5 years'}
Note: If a key already exists,
update()
will overwrite its value.
The advantages of the update()
method are as listed:
- Batch updates in one line
- Merges another dictionary or key-value iterable
- Overwrites existing keys with new values
- Cleaner and faster than multiple
[]
insertions
What if you want to add a key only if it doesn’t already exist? That’s where the setdefault()
method comes in.
Using setdefault()
to add items to a dictionary
The setdefault()
method in Python allows you to insert a key with a default value, but only if the key is not already present in the dictionary. If the key exists, the value is unchanged. This is useful when working with nested dictionaries, counters, or default initialization in loops.
Syntax of the setdefault()
method is:
dictionary.setdefault(key, default_value)
Parameters:
key
: The key to look for in the dictionary.default_value
(optional): The value to insert if the key is not already present. If omitted and the key is missing,None
is inserted by default.
Return value:
- Returns the value of the key if it exists.
- If the key doesn’t exist, inserts the key with the
default_value
and returns that value.
Example:
settings = {"theme": "dark", "notifications": True}# Add a new key if not presentsettings.setdefault("volume", 70)# Try to add an existing key-value won't changesettings.setdefault("theme", "light")print(settings)
The output of this code is:
{'theme': 'dark', 'notifications': True, 'volume': 70}
There are several reasons to use setdefault()
as follows:
- Ensures keys are only added if they don’t already exist
- Prevents accidental overwriting of values
- Great for default initialization in nested structures
- Available in all Python versions
If you need to merge dictionaries dynamically inside functions or unpack multiple mappings, unpacking with **
makes that easy.
Merge and add items using unpacking operator **
Starting with Python 3.5, you can use the unpacking operator (**
) to merge multiple dictionaries or add new key-value pairs while creating a new dictionary. This is a clean, modern approach for combining and extending dictionaries without mutating the original.
Syntax of the **
operator is:
new_dict = {**existing_dict, **another_dict, "new_key": value}
Parameters:
existing_dict
andanother_dict
: These unpack the key-value pairs from the given dictionaries into the new one."new_key": value
: A new key-value pair that is added explicitly during dictionary creation.
Return value:
A new dictionary containing merged key-value pairs.
Note: If duplicate keys exist, the last occurrence wins, i.e., values from
another_dict
or the manually added key overwrite earlier ones.
Example:
user = {"name": "Ava", "age": 25}additional_info = {"location": "Canada"}# Merge dictionaries and add a new keyupdated_user = {**user, **additional_info, "verified": True}print(updated_user)
This example gives the following output:
{'name': 'Ava', 'age': 25, 'location': 'Canada', 'verified': True}
Here are some reasons why dictionary unpacking is useful:
- Combines multiple dictionaries into one
- Keeps the original dictionaries unchanged
- Allows adding new keys alongside unpacked values
- Concise and readable for small merges
- Available from Python 3.5+
If you are still looking for a more straightforward way to merge entire dictionaries in Python 3.9 and above, then the union operator (|
) might be just what you need.
Add or merge dictionary items using union (|
) operator
Introduced in Python 3.9, the union operator (|
) is a sleek and intuitive way to add or merge dictionary items. It allows you to combine dictionaries or add new keys without modifying the original dictionary, returning a new one instead. This operator is a modern alternative to methods like update()
or unpacking with **
.
Syntax of the union operator is:
new_dict = dict1 | dict2
Parameters:
dict1
(left dictionary): The base dictionary whose items come first (may be overwritten).dict2
(right dictionary): The dictionary whose items are added or overwrite keys from dict1 if they overlap.
Return value:
Returns a new dictionary that combines the keys and values of both operands.
Note: If duplicate keys exist, the right-hand dictionary overwrites those from the left-hand dictionary.
Example:
defaults = {"font": "Arial", "size": 12}user_prefs = {"size": 14, "theme": "dark"}combined = defaults | user_prefsprint(combined)
The output of this code is:
{'font': 'Arial', 'size': 14, 'theme': 'dark'}
Some of the features of union operators are:
- It doesn’t change the original dictionaries
- Cleaner and shorter than
update()
or**
for merging - Ideal for modern Python codebases
- Great for quick, one-line dictionary combinations
However, if you are looking for a more manual way to add items to a dictionary, using a loop will be a better choice.
Add multiple items to a dictionary using a loop
One of the most common and flexible ways to add items to a dictionary is by using a loop. Whether you’re building a dictionary from scratch or adding new keys based on a condition, using dict[key] = value
inside a loop allows for dynamic, bulk insertion.
This method is especially useful in scenarios like reading data, processing lists, or taking user input.
Syntax of using a loop for adding items to a dictionary is:
for key, value in some_iterable:
dictionary[key] = value
Example:
items = ["apple", "banana", "cherry"]inventory = {}for i, fruit in enumerate(items):inventory[f"item_{i}"] = fruitprint(inventory)
The output produced by this code will be:
{'item_0': 'apple', 'item_1': 'banana', 'item_2': 'cherry'}
Using loops to add items to a dictionary provides the following:
- Supports dynamic key-value generation
- Ideal for bulk population from lists, files, APIs, etc.
- Works in any Python version
- Gives full control over key formatting and logic
Now that you’ve seen different ways to add items to dictionaries in Python, let’s summarize the techniques and help you choose the best one for your use case.
Comparison of all methods to add items to a Python dictionary
Different methods to add items to a dictionary in Python offer different benefits depending on the use case, whether you’re updating in place, preserving original data, or adding conditionally.
Here’s a quick comparison table to help you choose the right method:
Method | Overwrites existing keys | In-place modification | Python version |
---|---|---|---|
dict[key] = value |
Yes | Yes | All versions |
update() |
Yes | Yes | All versions |
setdefault() |
No (if key exists) | Yes | All versions |
Unpacking (** ) |
Yes | No | Python 3.5+ |
Union operator (| ) |
Yes | No | Python 3.9+ |
Loop | Yes | Yes | All versions |
Now you know multiple ways to add items to a Python dictionary, so choose the one that best fits your task and Python version!
Conclusion
Adding items to a Python dictionary is a fundamental skill for working with dynamic data. In this article, we explored seven different ways to insert key-value pairs—from basic methods like square bracket assignment and update()
, to more advanced options like dictionary unpacking and the union operator. We also compared these methods based on whether they overwrite existing keys, modify the dictionary in place, and their supported Python versions.
If you’d like to keep building your Python skills, check out the Learn Intermediate Python 3 course on Codecademy. It dives into topics like functions and object-oriented programming to help you level up your coding skills.
Frequently asked questions
1. How to check if an item is in a dictionary in Python?
Use the in
keyword to check if a key exists:
if "name" in my_dict:print("Key exists")
2. How to add two dictionaries in Python?
Use the union operator |
(Python 3.9+) or the update()
method:
# Using union operatormerged = dict1 | dict2# Using update()dict1.update(dict2)
3. How to check if a dictionary is empty in Python?
You can check if a dictionary is empty by using the len()
function:
if len(my_dict) == 0:print("Dictionary is empty")
4. Can dictionary keys be of any data type?
No, keys must be immutable types such as strings, numbers, or tuples containing only immutable elements.
5. What happens if I assign a value to an existing key?
The old value is overwritten with the new one. Dictionaries do not allow duplicate keys.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
What Is Dictionary Comprehension in Python?
Learn how to write powerful, concise code using dictionary comprehension in Python. In this tutorial, you will learn what Python dictionary comprehension is, how it works, and why it is a valuable tool. - Article
How to Sort a Dictionary by Key or Value in Python
Learn how to sort Python dictionaries by keys or values using built-in functions like `sorted()` and handle edge cases with `OrderedDict`. - Article
A Guide to Python Data Structures
Learn the fundamentals of Python data structures in this comprehensive guide, covering different types, examples, and ideal scenarios for using them efficiently.
Learn more on Codecademy
- Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours - Free course
Learn Swift: Arrays, Sets, and Dictionaries
Continue your Swift journey by learning these collection types: arrays, sets, and dictionaries!Beginner Friendly4 hours - Free course
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Intermediate3 hours
- What is a dictionary in Python?
- Adding items to the dictionary using square brackets (`[]`)
- How to add multiple items to a dictionary using `update()`
- Using `setdefault()` to add items to a dictionary
- Merge and add items using unpacking operator `**`
- Add or merge dictionary items using union (`|`) operator
- Add multiple items to a dictionary using a loop
- Comparison of all methods to add items to a Python dictionary
- Conclusion
- Frequently asked questions