How to Add Value to a Dictionary in Python

How-to basics · Updated November 23, 2026

Adding a value to a dictionary in Python is a fundamental operation that lets you store, update, or insert key-value pairs. The most direct way is to assign a value to a key using square brackets: my_dict["key"] = "value". If the key already exists, this updates its value; if not, it creates a new entry. This guide covers all common methods—direct assignment, the update() method, setdefault(), and dictionary unpacking—along with practical examples and pitfalls to avoid.

What You’ll Need

  • Python 3.x installed (any recent version works; examples are tested on Python 3.10+).
  • A text editor or IDE (e.g., VS Code, PyCharm, or IDLE) to write and run your code.
  • Basic familiarity with Python syntax, such as variables and print statements.

Step-by-Step

  1. Create a dictionary (if you don’t have one). Use curly braces with key-value pairs separated by colons. For example: my_dict = {"name": "Alice", "age": 30}. If you start with an empty dictionary, use {}.
  2. Add a new key-value pair using square bracket assignment. Write my_dict["city"] = "New York". This adds a new entry if the key doesn’t exist, or updates the value if it does. For instance, my_dict["age"] = 31 would change the age to 31.
  3. Use the update() method to add multiple pairs at once. Pass a dictionary or an iterable of key-value pairs. Example: my_dict.update({"country": "USA", "job": "Engineer"}). This adds or updates all specified keys.
  4. Use setdefault() to add a key only if it doesn’t already exist. Write my_dict.setdefault("nickname", "Al"). If the key is missing, it adds it with the given value; if present, it leaves the existing value unchanged. This is useful for defaults.
  5. Add a key-value pair using dictionary unpacking (Python 3.5+). Create a new dictionary that merges the original with new pairs: new_dict = {**my_dict, "hobby": "reading"}. This creates a new dictionary; the original remains unchanged. To modify in place, assign the result back: my_dict = {**my_dict, "hobby": "reading"}.
  6. Add a value to a key that holds a list or another mutable object. If the value is a list, you can append: my_dict.setdefault("tags", []).append("python"). This creates an empty list if the key doesn’t exist, then appends. Similarly, for a set, use setdefault("tags", set()).add("python").
  7. Verify the addition. Print the dictionary or check the key: print(my_dict) or if "city" in my_dict: print(my_dict["city"]).

Common Mistakes

  • Using a mutable default with setdefault() incorrectly. Calling setdefault("key", []) creates a new list each time, but that’s fine. The mistake is using a shared mutable object as the default, like default_list = [] and then setdefault("key", default_list)—if you modify the returned list, it modifies the shared list, affecting other keys. Always use an immutable default or create a new list inside the call.
  • Forgetting that assignment overwrites existing values. If you write my_dict["age"] = 31 when age already exists, it replaces the old value. If you need to keep the old value, check first or use setdefault().
  • Using update() with a non-dict iterable incorrectly. update() expects key-value pairs, like a list of tuples: my_dict.update([("a", 1), ("b", 2)]). Passing a list of single values raises a ValueError.
  • Modifying a dictionary while iterating over it. Adding or removing keys inside a for loop can cause a RuntimeError. Collect changes in a separate list or copy first.
  • Assuming order is preserved in older Python versions. Dictionaries are ordered in Python 3.7+, but if you’re on Python 3.6 or earlier, order is not guaranteed. For most addition tasks, order doesn’t matter, but be aware if you rely on it.

Tips

  • Use setdefault() when you want to initialize a key with a default value only if it doesn’t exist, especially for counters or lists.
  • For merging two dictionaries, prefer the | operator in Python 3.9+: merged = dict1 | dict2. This creates a new dictionary, and keys from the right override those on the left.
  • To add many keys with the same value, use dict.fromkeys(keys_list, value), but be careful with mutable values—they are shared across all keys.
  • When adding a value that requires computation, consider using a conditional expression: my_dict["total"] = my_dict.get("total", 0) + 1 to increment a counter without a separate check.
  • Always use meaningful key names to keep your dictionary readable and maintainable.

Troubleshooting

  • KeyError when accessing a key after adding? If you try to read a key that wasn’t added, Python raises a KeyError. Use my_dict.get("key") to return None instead, or my_dict.get("key", "default") for a fallback.
  • Value not updating as expected. Check if you’re using setdefault()—it only sets if the key is missing. If you need to always update, use direct assignment.
  • TypeError: ‘dict’ object is not callable. This happens if you named a variable dict and then tried to call it. Avoid shadowing built-in names; rename your variable.
  • Unhashable type when using a list as a key. Keys must be immutable. Use a tuple instead: my_dict[(1, 2)] = "value".
  • Memory error when adding many entries. This is rare, but if you’re adding millions of items, consider a more memory-efficient structure like a database or a defaultdict from collections if it fits.

Frequently Asked Questions

  • Can I add a value to a dictionary without specifying a key? No, every value in a dictionary must be associated with a unique key. If you need an ordered collection of values without keys, use a list or set.
  • What is the difference between update() and direct assignment? Direct assignment adds or updates a single key. update() can add multiple keys at once from a dict or iterable, and it also updates existing keys.
  • How do I add a value to a nested dictionary? Access the inner dictionary first: my_dict["outer"]["inner"] = "value". If the outer key doesn’t exist, you’ll get a KeyError; use setdefault() to create it: my_dict.setdefault("outer", {})["inner"] = "value".
  • Can I add a value to a dictionary in a loop? Yes, simply assign inside the loop: for i in range(5): my_dict[i] = i*2. This adds or updates keys each iteration.
  • Is there a way to add a value only if the key doesn’t exist, without overwriting? Yes, use setdefault() or check with if key not in my_dict: before assigning.
  • What happens if I add a key with the same name as an existing one? The existing value is overwritten with the new value. The dictionary keeps only one entry per key.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.