Create a list and append the resulting dict there, no need to update the same dict over and over Answer from Deleted User on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-add-to-dictionary-without-overwriting
Python Add to Dictionary Without Overwriting - GeeksforGeeks
July 23, 2025 - In conclusion above, methods provide simple and effective ways to add key-value pairs to a dictionary in Python without overwriting existing entries. Depending on your specific use case, you can choose the method that best fits your needs.
🌐
Reddit
reddit.com › r/learnpython › how to append two dictionaries so they dont overwrite each other?
r/learnpython on Reddit: How to append two dictionaries so they dont overwrite each other?
February 16, 2023 -

I have a script that continuosly generates dictionaries with the same keys but different values. I want to write the results out in a json file but to do that i need to do load & dump into the file.

with open('sample.json') as f:
    data = json.load(f)

data.update(results)

with open('sample.json', 'w') as f:
    json.dump(data, f)

The above code only overwrites the existing data it doesn't append it. I figured it is beacuse the dictionaries have the same keys because if i try it with a different dictionary template, the append does happen.

Is there a way to append similar dictionaries without overwriting?

Top answer
1 of 2
1

TLDR

Instead of

my_dict[word] = count

You may want to use

my_dict[word] = my_dict[word] + [count]

This is assuming:

  • count is the line(s) that the word was found in
  • you want each key to have a list of count denoting which lines the word was found on

Explanation

To assign values to a dict you assign to a specific key in the same way that you might assign a value to an index of a list. You did that in this line here:

# assign value "count" to dict "my_dict" at key "word"
my_dict[word] = count

So you're already partway there! What we want now is to add to a preexisting value. Remembering that in Python assignment replaces the value of a variable, then we want to be careful to assign with our updated value. With int variables we do this by taking the previous value and adding to it (ex a = a + 2), likewise to add to a list in a dict key we take the previous value and assign that plus what was added to it.

Example

my_dict = {}                       # {}
my_dict["a"] = [1]                 # {"a": [1]}
my_dict["a"] = my_dict["a"] + [2]  # {"a": [1, 2]}

This works because my_dict["a"] evaluates to it's current value (a list), and you can then append another list to that list to create a list with the values of both lists. Like

list_a = [1, 2]
list_b = [3, 4]
list_a = list_a + list_b  # == [1, 2, 3, 4]

Cool Tip

Since the operation of adding to an existing value is common in Python, it actually has a shorthand for this pattern.

Instead of

a = a + 2

You also have the option to write the shorthand of that which is

a += 2
2 of 2
0

May be this is what you want not sure.if word not in dict initiate a empty list. Then append when found.use strip removetrailing characters.

def inverse_index():
        my_dict = {}
        with open('doc0.txt','r') as f:
          for count, value in enumerate(f):
            for word in value.strip().split():
               if(word.strip() not in my_dict):
                   my_dict[word.strip()] = []
               print(count, word.strip())              
               my_dict[word.strip()].append(count)
        print(my_dict)
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-add-to-dictionary
How to Add and Update Python Dictionaries Easily | DigitalOcean
October 16, 2025 - Below are some advanced patterns for updating dictionaries in Python, complete with clear explanations. Problem: If you want to add new key-value pairs from one dictionary to another but avoid overwriting any existing keys, you need more control than the standard update() method offers.
🌐
DataCamp
datacamp.com › tutorial › python-dictionary-append
Python Dictionary Append: How to Add Key-Value Pairs | DataCamp
August 6, 2024 - In this example, the .setdefault() method adds the 'city' key with the value 'New York' because it did not already exist in the dictionary. When trying to add the 'age' key, it does not change the existing value 25 because the key already exists.
🌐
Codecademy
codecademy.com › article › python-dictionary-append-how-to-add-items-to-dictionary
Python Dictionary Append: How to Add Items to Dictionary | Codecademy
... If you are still looking for a more straightforward way to merge entire dictionaries in Python 3.9 and above, then the union operator (|) might be just what you need. Introduced in Python 3.9, the union operator (|) is a sleek and intuitive ...
Find elsewhere
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python dictionary append: how to add key/value pair?
Python Dictionary Append: How To Add Key/Value Pair?
October 14, 2024 - Yes, you can. When you use the update() method to append dictionary python, existing keys are updated with new values, but if there are any new keys, they are added to the dictionary without overwriting existing ones.
🌐
GeeksforGeeks
geeksforgeeks.org › merge-dictionaries-without-overwriting-in-python
Merge Dictionaries without Overwriting in Python - GeeksforGeeks
February 19, 2024 - The ** unpacking operator is utilized to merge their contents into a new dictionary named merged_dict. This concise approach combines the key-value pairs from both dictionaries, and if there are overlapping keys, the values from dict2 will overwrite ...
🌐
Codecademy
codecademy.com › forum_questions › 50e803f39874383aac002863
Why does this overwrite the existing key-value pair, rather than create a new pair? | Codecademy
Here is my correct code for 3.3 (Dictionaries - Changing Your Mind) # key - animal_name : value - location zoo_animals = { 'Unicorn' : 'Cott...
🌐
YouTube
youtube.com › watch
How to Update a Python Dictionary Without Overwriting Previous Values - YouTube
Learn how to effectively manage data in Python by adding new elements to dictionaries without overwriting existing values. Perfect for handling JSON.---This ...
Published   March 28, 2025
Views   7
🌐
Stack Overflow
stackoverflow.com › questions › 54161029 › adding-more-values-to-a-key-in-a-dictionary-without-overwriting-the-existing-val › 54161573
python - Adding more values to a key in a dictionary without overwriting the existing value - Stack Overflow
My problem still remains, the add function that i use for other keys in the dictionary looks the same as player["points"] = {correct_guess}if that helps? ... Initialize it to [] or list(). If you include more code in your question, I could be more specific... ... With player["points"] = {correct_guess} you're correct_guess variable turns into a set object due to the curly braces. You could then operate with this object according to PythonDocs Set Types.
🌐
pythontutorials
pythontutorials.net › blog › adding-more-values-on-existing-python-dictionary-key
How to Add More Values to an Existing Python Dictionary Key Without Overwriting Data — pythontutorials.net
Store multiple values in a **container** (like a list or set) and add new values to this container instead of reassigning the key. This blog will guide you through proven methods to add values to a dictionary key without overwriting existing data, with step-by-step examples and best practices.