Use defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list) # create the dictionary, then populate it.
>>> d.update({"TIM":[['xx', 'yy'], ['aa', 'bb']], "SAM":[['yy', 'cc']]})
>>> d # see its what you wanted.
defaultdict(<type 'list'>, {'TIM': [['xx', 'yy'], ['aa', 'bb']], 'SAM': [['yy', 'cc']]})
>>> d["SAM"].append(['tt','uu']) # add more items to SAM
>>> d["KIM"].append(['ii','pp']) # create and add to KIM
>>> d # see its what you wanted.
defaultdict(<type 'list'>, {'TIM': [['xx', 'yy'], ['aa', 'bb']], 'KIM': [['ii', 'pp']], 'SAM': [['yy', 'cc'], ['tt', 'uu']]})

If you want the dictionary values to be sets, that is no problem:

>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> d.update({"TIM":set([('xx', 'yy'), ('aa', 'bb')]), "SAM":set([('yy', 'cc')])})
>>> d["SAM"].add(('tt','uu'))
>>> d["KIM"].add(('ii','pp'))
>>> d
defaultdict(<type 'set'>, {'TIM': set([('xx', 'yy'), ('aa', 'bb')]), 'KIM': set([('ii', 'pp')]), 'SAM': set([('tt', 'uu'), ('yy', 'cc')])})
Answer from Inbar Rose on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › equivalent of dictionary.update() but for appending when value is a collection?
r/learnpython on Reddit: Equivalent of dictionary.update() but for appending when value is a collection?
July 20, 2024 -

I just learned about the update method while doing some work. I had been writing if statements to check if key is in .keys() for so long. Is there an equivalent for "add key: value if not already in dictionary, otherwise update the value"?

For example to replace:

if ind in collection.keys():
  collection[ind].append(x)
else:
  collection[ind] = [x]
Top answer
1 of 2
2
There is not an exact equivalent, but there are things that are similar. I would suggest using a default dict: import collections d = collections.defaultdict(list) d[5].append(4) But if it had to be a standard dictionary, you could do d[ind] = d.get(ind, []) + [x] Note: the second will not modify existing lists in place, which may or may not be a problem. EDIT: Per u/commy2 's reply below, setdefault is better way if you're restricted to regular dictionaries - especially if your lists will be getting long so that copying them is nontrivial, or if it's important to modify the lists in place.
2 of 2
1
I don't believe it's possible to do what you want with update(). The dictionary documentation for update() says: update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Note the emphasized text. The comment by u/ferricdonkey mentions using a defaultdict and that works perfectly to replace the code example that you showed. Like this: import collections collection = collections.defaultdict(list) collection[1] = [2] x = 42 ind = 1 # change to a key NOT in "collections" and run again collection[ind].append(x) print(collection) But your example isn't using update(). If you want to do what update() does but have it append to existing key values, you have to write a function to do that: import collections def ddict_update(ddict, upd): """Update a dictionary with either a dictionary or a sequence. Any existing key values are appended to, not replaced. """ if isinstance(upd, dict): for (key, val) in upd.items(): ddict[key].append(val) else: for (key, val) in upd: ddict[key].append(val) # make a test dictionary collection = collections.defaultdict(list) collection[1] = [2] update = {1: 42, 0: 42} # update with a dictionary ddict_update(collection, update) print(collection) update = [(3, 3), (1, 999)] # update with a sequence of tuples ddict_update(collection, update) print(collection) This does what you want, I think. The function can be simpler if you always update the dictionary with either another dictionary or a sequence.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-add-to-dictionary
How to Add and Update Python Dictionaries Easily | DigitalOcean
October 16, 2025 - This will add a new key-value pair to the dictionary. If the key already exists, its value will be updated. ... You cannot directly use methods like .append() for dictionaries as they are used for lists. However, you can add a key-value pair using dictionary[key] = value.
🌐
GeeksforGeeks
geeksforgeeks.org › python-dictionary-update-method
Python Dictionary update() method - GeeksforGeeks
December 9, 2024 - Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
🌐
Data Science Parichay
datascienceparichay.com › home › blog › python add or update item in dictionary
Python Add or Update Item in Dictionary - Data Science Parichay
October 4, 2020 - update() is a dictionary function in python used to update a dictionary by changing the values of existing keys or adding new keys.
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › python-dictionary-append
Python Dictionary Append: How to Add Key-Value Pairs | DataCamp
August 6, 2024 - Learn how to append key-value pairs in a Python dictionary using methods such as square bracket notation, .update() for bulk additions, and .setdefault() for conditional inserts.
🌐
Python Guides
pythonguides.com › python-dictionary-update
Python Dictionary Update
January 12, 2026 - In the example above, I updated the entry for Texas and added Massachusetts and New York in one go. The Python dictionary .update() method is “in-place,” meaning it modifies the original object directly.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.3 documentation
Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
🌐
Reddit
reddit.com › r/cs50 › dictionary update method replaces instead of updating
r/cs50 on Reddit: Dictionary Update Method Replaces Instead of Updating
April 8, 2022 -

I've completed DNA and submitted for full credit using lists instead of dictionaries. DNA was really enthralling to me for some reason and I'm going back and trying to make my code both more pythonic and attempting to get it better optimized. Part of my motivation is that I just don't feel anywhere near as comfortable with dictionaries as I did coming out of previous weeks' psets that had similar, heavier (for me) concepts.

One specific area that's giving me trouble in my understanding is the .update() method. I'm using it to store the small.csv info into a dict named STR. I had thought it was the analogue of .append() for lists but, after trying to incorporate it into my revamped DNA, it will update for the first row of the CSV being read on the first iteration but then it just continually replaces that single row/entry in the dict with each iteration. I'm sure I'm just not grasping something fundamental about dicts and/or update() but am not knowledgeable enough yet to know what that might be. I'm not even sure it's technically necessary to be storing the database csv or if it's better to work with the CSV in-place.

Could someone please help me understand why my expectation of update() is flawed?

The code below only stores the last line of the small.csv database:

{'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}

    # Open person STR profiles csv and append to STR list

    with open(sys.argv[1], 'r', newline = '') as file:
        reader = csv.DictReader(file)
        for row in reader:
            STR.update(row)
🌐
Note.nkmk.me
note.nkmk.me › home › python
Add and Update an Item in a Dictionary in Python | note.nkmk.me
August 25, 2023 - This article explains how to add an item (key-value pair) to a dictionary (dict) or update the value of an existing item in Python. Add or update a single item in a dictionary Add or update multiple i ...
🌐
Codecademy
codecademy.com › article › python-dictionary-append-how-to-add-items-to-dictionary
Python Dictionary Append: How to Add Items to Dictionary | Codecademy
The advantages of the update() method are as listed: ... What if you want to add a key only if it doesn’t already exist? That’s where the setdefault() method comes in. 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.
🌐
TechBeamers
techbeamers.com › python-dictionary
Python Dictionary – Create, Append, Update, Remove
November 30, 2025 - In this tutorial, you’ll learn what is Python dictionary and how to create it. It will also teach you how to add/append to a Python dictionary, sort it by value, search, iterate, and remove elements.
🌐
Finxter
blog.finxter.com › home › learn python blog › python dictionary append – 4 best ways to add key/value pairs
Python Dictionary Append - 4 Best Ways to Add Key/Value Pairs - Be on the Right Side of Change
February 11, 2023 - This was done to illustrate that the update() method overwrites rather than appends. Please note though for the remainder of the article we will assume that the ‘course’ key contains the list ['Maths', 'Science'] as previously shown. In addition to the built-in dictionary update() method, Python lists have a built-in append() method.
🌐
Guru99
guru99.com › home › python › python dictionary append: how to add key/value pair
Python Dictionary Append: How to Add Key/Value Pair
August 13, 2025 - We can make use of the built-in function append() to add elements to the keys in the dictionary.
🌐
Programiz
programiz.com › python-programming › methods › dictionary › update
Python Dictionary update()
Become a certified Python programmer. Try Programiz PRO! ... The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
🌐
Studytonight
studytonight.com › python › dictionaries-in-python
Python Dictionaries - Create, Append, Delete and Update | Studytonight
Dictionaries in Python. In this tutorial you will learn about Dictionaries in python. It covers how to create a dictionary, how to access its elements, delete elements, append elements to dictionary, update a dictionary etc.