Add New Item to Dictionary Python: Step-by-Step
In this article
To add a new item to a Python dictionary, assign a value to a new key using square brackets: my_dict["new_key"] = value. This adds the key-value pair if the key does not already exist, and updates it if it does. You can also use the update() method to add multiple items at once, or setdefault() to add a key only if it is missing. No imports or special setup are needed beyond a working Python installation.
What You'll Need
- Python 3 installed on your computer (any recent version works; the syntax below is standard in Python 3.x).
- A way to run Python code: the interactive interpreter, a script file, or an IDE such as VS Code or PyCharm.
- A dictionary to work with. You can create one with
my_dict = {}or start with existing data.
Step-by-Step
- Create or open your dictionary. If you already have a dictionary variable, use it. Otherwise, define one:
my_dict = {"name": "Alex", "age": 30} - Choose a new key. Keys must be immutable types such as strings, numbers, or tuples. For example, use
"city"as a string key. Avoid using lists or other dictionaries as keys because they are unhashable and will raise aTypeError. - Assign the value using square brackets. Write the dictionary name, the new key in square brackets, an equals sign, and the value:
This adds the pairmy_dict["city"] = "London""city": "London"to the dictionary. If the key already exists, its value is overwritten. - Verify the addition. Print the dictionary to confirm the new item is present:
You should see the original keys plus the new one.print(my_dict) - Add multiple items at once (optional). Use the
update()method with another dictionary or an iterable of key-value pairs:
This adds both keys in one call.my_dict.update({"country": "UK", "job": "Engineer"})update()also overwrites existing keys with new values. - Add a key only if it does not exist (optional). Use
setdefault():
Ifmy_dict.setdefault("email", "alex@example.com")"email"is already present,setdefault()returns the existing value and does not change it. If absent, it inserts the new key with the given value. - Handle nested dictionaries (optional). If your dictionary contains another dictionary as a value, access the inner dictionary first, then assign:
This creates a nested structure. Make sure the inner dictionary exists before assigning to its keys, or you will get amy_dict["address"] = {} my_dict["address"]["street"] = "Main Street"KeyError.
Common Mistakes
- Using a mutable key. Lists, sets, and dictionaries cannot be keys because they are unhashable. Use a tuple or string instead.
- Forgetting that assignment overwrites.
my_dict["key"] = valuereplaces any existing value for that key. If you need to keep the old value, check withif "key" not in my_dict:before assigning, or usesetdefault(). - Calling
update()incorrectly.update()expects a dictionary or an iterable of key-value pairs, not two separate arguments. For a single pair, square-bracket assignment is simpler. - Assuming
setdefault()always adds. It only adds when the key is missing; otherwise it returns the existing value and leaves the dictionary unchanged. - Modifying a dictionary while iterating over it. Adding keys during a
forloop over the same dictionary can raise aRuntimeError. Collect changes first or iterate over a copy.
Tips
- Use descriptive string keys to keep dictionaries readable.
- For bulk additions, build a second dictionary and call
update()once; it is clearer than many separate assignments. - Use
collections.defaultdictwhen you frequently add to missing keys and want automatic default values, but note it requires an import. - Remember that dictionaries preserve insertion order in Python 3.7 and later, so new items appear at the end when printed.
- If you need to add to a list stored as a value, retrieve the list and append to it:
my_dict["tags"].append("new"). Ensure the key exists and holds a list first.
Troubleshooting
If the new item does not appear, check that you assigned to the correct variable and that you are printing the same dictionary. A common cause is reassigning the dictionary inside a function without returning it, so the caller never sees the change.
If you get a TypeError: unhashable type, your key is a list, set, or dictionary. Convert it to a tuple or use a string.
If you get a KeyError when working with nested dictionaries, the parent key does not exist yet. Create the inner dictionary first, as shown in step 7.
If update() raises ValueError, the argument is not a sequence of pairs. Pass a dictionary or a list of two-item tuples.
If changes seem lost after a function call, remember that dictionaries are mutable and passed by reference; modifications inside a function affect the original unless you explicitly copy it. Use my_dict.copy() for a shallow copy if you need to preserve the original.
Frequently Asked Questions
Can I add a key without a value?
No. Every key in a Python dictionary must have a value. You can assign None as a placeholder: my_dict["key"] = None.
What happens if I add a key that already exists?
The assignment overwrites the existing value. To avoid overwriting, check membership first with if key not in my_dict: or use setdefault().
How do I add multiple items at once?
Use update() with a dictionary or an iterable of key-value pairs. For example: my_dict.update({"a": 1, "b": 2}).
Can I use a number as a key?
Yes. Integers and floats are immutable and hashable, so they work as keys. Just be consistent with the type you use to look them up.
Does adding an item change the order of existing keys?
No. In Python 3.7 and later, dictionaries maintain insertion order, and new keys are added at the end. Existing keys keep their positions.
Is there a limit to how many items I can add?
No fixed limit is imposed by the language; the practical limit depends on available memory. Very large dictionaries may slow down lookups slightly, but adding items remains efficient on average.