A Complete Guide to Adding Items to Python Dictionaries

1. What is a Python dictionary (dict)

A Python dictionary (dict) is a data type that stores key‑value pairs, enabling highly efficient data management. Unlike lists or tuples, a dictionary does not maintain order, but it allows you to quickly retrieve values using keys. It is one of the most commonly used data types in Python programs.

Basic characteristics of dictionaries

  • Key‑value pairs: A dictionary consists of unique keys and their corresponding values. Keys must be of an immutable type (such as strings or numbers), while values can be of any type.
  • No ordering: Python dictionaries have no storage order, so you look up values by specifying a key.
  • Value lookup: You can quickly reference a value by specifying its key.

Example of creating a dictionary

The following example demonstrates the basic operations of creating a dictionary and retrieving values using keys.
Creating a dictionary

my_dict = {
"apple": "apple",
"banana": "banana",
"cherry": "cherry"
}

Retrieving a value

print(my_dict["apple"]) # Output: apple

2. Basic method for adding elements to a Python dictionary

In Python, you add elements to an existing dictionary using a simple assignment statement. This approach is intuitive and easy to understand even for those handling dictionaries for the first time.

Basic way to add elements

The syntax for adding a new element to a dictionary is as follows.
Adding a new element

my_dict["orange"] = "orange"
print(my_dict)

Output: {'apple': 'apple', 'banana': 'banana', 'cherry': 'cherry', 'orange': 'orange'}
With this method, if the specified key does not exist, a new element is added. However, if you use an existing key, its value will be overwritten, so you need to be aware of that.

Overwriting when using the same key

If you add a new value to a dictionary using an existing key, that value is overwritten.
my_dict["banana"] = "banana juice"
print(my_dict)

Output: {'apple': 'apple', 'banana': 'banana juice', 'cherry': 'cherry', 'orange': 'orange'}
In this way, the value for the already existing key "banana" is changed, and the original value is overwritten.

3. How to Add Elements to a Dictionary While Avoiding Overwrites

If you want to avoid overwriting, use the setdefault() method. This method adds a new element only when the specified key does not already exist in the dictionary, so you don’t have to worry about accidentally overwriting a value.

setdefault() Example

The following code demonstrates how to use setdefault() to add a new element without overwriting existing ones.
my_dict.setdefault("banana", "banana smoothie")
my_dict.setdefault("grape", "grape")
print(my_dict)

Output: {'apple': 'apple', 'banana': 'banana juice', 'cherry': 'cherry', 'orange': 'orange', 'grape': 'grape'}
In this example, the key "banana" already exists, so its value is not overwritten, and only the new key "grape" is added.</final
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

4. How to Merge Multiple Dictionaries and Add Elements

When merging multiple dictionaries into one, you can use the update() method. This allows you to add elements from another dictionary all at once, making data management more efficient.

update() Method Example

Below is an example of merging two dictionaries using the update() method.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
print(dict1)

Output: {'a': 1, 'b': 3, 'c': 4}
In this example, because the key "b" exists in both dictionaries, the value in dict1 was overwritten by the value from dict2. The new key "c" was added to dict1.

How to Avoid Overwrites

If you want to merge dictionaries without overwriting, you can combine setdefault() with a for loop.
for key, value in dict2.items():
dict1.setdefault(key, value)
print(dict1)

Output: {'a': 1, 'b': 2, 'c': 4}

5. Advanced Technique: Adding Elements Conditionally

In real-world development, there are cases where you add elements to a dictionary based on conditions. For example, when you only add elements that meet specific criteria to a dictionary, you can dynamically add them using if statements or for loops.

Example of Adding Elements Conditionally

The following code shows an example of adding only fruits whose price meets a certain threshold to the dictionary.
items = [("apple", 100), ("banana", 150), ("cherry", 200)]
fruit_dict = {}

for fruit, price in items:
if price > 120:
fruit_dict[fruit] = price

print(fruit_dict)

Output: {'banana': 150, 'cherry': 200}
In this example, only fruits with a price above 120 are added to the dictionary. When adding elements to a dictionary conditionally, you can achieve this kind of flexible processing.
年収訴求

6. Error Handling When Working with Dictionaries

A common error that occurs when manipulating dictionaries is KeyError. This error occurs when the specified key does not exist in the dictionary. To avoid the error, it’s common to check for the key’s existence or use the get() method.

How to Avoid KeyError

The following example shows how to avoid the error using the get() method.
value = my_dict.get("pear", "Key not found")
print(value)

Output: Key not found
In this way, accessing a non‑existent key does not raise an error and returns a default value.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール