Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Dictionary Append or Update: How-To Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To append or update a Python dictionary, assign a value to a key with square brackets: d['key'] = value. If the key exists, its value is replaced; if not, the key-value pair is added. For multiple pairs at once, use d.update({...}) or the |= operator (Python 3.9+). That single line is the whole answer; the rest of this guide covers the variations, the traps, and how to choose the right method.

What You'll Need

  • Python 3 installed (any recent version; the |= operator needs 3.9 or later).
  • A text editor or IDE to run snippets.
  • Basic familiarity with dictionary syntax: curly braces, colons, and comma-separated key-value pairs.

Step-by-Step

  1. Create or identify your dictionary. Start with an empty dict or an existing one: d = {} or d = {'a': 1}. Dictionaries are mutable, so you can change them in place without reassigning.

  2. Add or update a single key with bracket assignment. Write d['b'] = 2. If 'b' is new, it is appended; if it existed, the old value is overwritten. This is the most common and fastest way for one pair.

  3. Add multiple pairs with update(). Call d.update({'c': 3, 'd': 4}). You can also pass keyword arguments: d.update(e=5, f=6). Existing keys are overwritten; new keys are added. update() returns None, so do not assign its result.

  4. Use the merge operator for a concise alternative. In Python 3.9+, d |= {'g': 7} updates in place. For a new dictionary without mutating the original, use merged = d | {'h': 8}. Both require 3.9+; on older versions use update() or {**d, 'h': 8}.

  5. Append to a list stored inside the dictionary. If d['items'] is a list, do d.setdefault('items', []).append(new_item). This creates the list if missing and appends safely. Alternatively, check if 'items' in d: then append, else assign a new list.

  6. Update only if the key is absent. Use d.setdefault('key', default_value). It sets the key only when missing and returns the existing value otherwise. This avoids overwriting data you meant to keep.

  7. Merge nested dictionaries carefully. A plain update() replaces a nested dict entirely. To merge deeply, loop over the inner keys: for k, v in new.items(): d.setdefault(k, {}).update(v). For complex cases, consider a recursive helper or a library, but the loop covers most needs.

  8. Verify the result. Print the dictionary or check specific keys with d.get('key'). Confirm that existing values were overwritten as intended and new keys appear.

Common Mistakes

  • Using append() on a dictionary. Dictionaries have no append method; that belongs to lists. Use bracket assignment or update().
  • Assigning the result of update(). d = d.update({...}) sets d to None. Call it without assignment.
  • Assuming update() merges nested dicts. It overwrites at the top level. Merge inner keys explicitly if you need deep merging.
  • Mutating a dictionary while iterating over it. Adding or deleting keys during a for loop raises RuntimeError: dictionary changed size during iteration. Iterate over a copy: for k in list(d):.
  • Using unhashable keys. Lists and other dicts cannot be keys; use tuples or strings instead.
  • Forgetting that keys are case-sensitive. 'Name' and 'name' are different keys, so an update may create a duplicate rather than overwrite.

Tips

  • Use d[key] = value for one pair; it is clear and fast.
  • Use update() when merging another dictionary or an iterable of pairs.
  • Use setdefault() to append to a list value without a separate existence check.
  • Use |= for in-place merging in modern Python; use | when you need a new dict and want to keep the original unchanged.
  • Remember that update() accepts any iterable of key-value pairs, including a list of tuples.
  • For readability, avoid chaining too many operations; a short loop is often clearer than a dense one-liner.

Troubleshooting

  • KeyError when reading a key you thought you added. Check spelling and case. Use d.get('key') to avoid the error and see whether the key exists.
  • Update seems to do nothing. Confirm you are not reassigning the result of update(). Also check that the variable you print is the same object you updated.
  • Nested data disappeared. A top-level update() replaced the inner dict. Rebuild the nested structure or merge inner keys manually.
  • RuntimeError during iteration. Collect changes in a separate list and apply them after the loop, or iterate over list(d.items()).
  • TypeError: unhashable type. You used a list or dict as a key. Convert to a tuple or string.
  • Unexpected order. Dictionaries preserve insertion order in Python 3.7+, but updating an existing key keeps its original position; new keys go to the end. If order matters, build a new dict in the desired order.

Frequently Asked Questions

Can I append to a dictionary in Python?

Dictionaries do not have an append method. You add or update entries by assigning to a key: d['new'] = value. To append to a list stored as a value, use d.setdefault('list_key', []).append(item).

What is the difference between update() and bracket assignment?

Bracket assignment sets one key. update() sets many keys from another dictionary or an iterable of pairs. Both overwrite existing keys and add new ones.

How do I merge two dictionaries without changing the original?

Use merged = {**d1, **d2} or, in Python 3.9+, merged = d1 | d2. Both create a new dictionary; the originals stay unchanged.

Does update() overwrite existing keys?

Yes. Any key present in both the original and the update source takes the new value. Keys only in the original remain.

How do I add a key only if it does not exist?

Use d.setdefault('key', default). It adds the key with the default only when missing and returns the existing value otherwise.

Why do I get RuntimeError: dictionary changed size during iteration?

You modified the dictionary while looping over it. Iterate over a copy, such as for k in list(d):, or collect changes and apply them after the loop.