In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.
Answer from Anand S Kumar on Stack Overflow
Top answer
1 of 5
58

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.
2 of 5
15

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]
🌐
GeeksforGeeks
geeksforgeeks.org › python › adding-items-to-a-dictionary-in-a-loop-in-python
Adding Items to a Dictionary in a Loop in Python - GeeksforGeeks
July 23, 2025 - res[j] = b[i] adds the key-value pair to the dictionary res. This method initializes a dictionary with predefined keys and default value which can then be updated with a loop.
🌐
Reddit
reddit.com › r/learnpython › how to append to dictionary within a for loop
r/learnpython on Reddit: How to append to dictionary within a for loop
July 24, 2022 -

Hello, I'm trying to compare the kappa scores for one person against other people. I want to generate a dataframe that has the kappa for person A vs person B, person A vs person C, person A vs person D, etc.

To do this, I was thinking of reading in a everyone's scores that they gave as a dataframe, and assigning them to a dictionary. So something like {person B : person_B_scores_df, person C: person_C_scores}

But I can't figure out how to iterate over a for loop and add the key pairings to a dictionary. I keep getting a key error. Here is my code.

   ## Create list of raters
    rater_list = ["person_A", "person_B", "person_C", "person_D"]
    rater_dict = {} 
    
    ## Pull in each rater's scores and add them key/value pairing in rater_dict 
    for name in rater_list:
        rater_df = pd.read_csv(input_path/f"rater_scores_{name}.csv")
        rater_dict[name].append(rater_df)

    ## Also tried the following!! - The code below only appends the last person in the rater list to the dictionary 
    #for name in rater_list:
     #   rater_df = pd.read_csv(input_path/f"rater_scores_{name}.csv")
     #   rater_dict={name:rater_df}
Top answer
1 of 3
2
# Adding the entry {'Team_A' : 10} to a dict my_dict = {} my_dict['Team_A'] = 10 # Retrieving the value from a dict team_a_score = my_dict['Team_A'] print(team_a_score) # prints 10 ---------------------------------- He's a simplified version of what you currently have names_list = ['person_A', 'person_B', 'person_C'] d = {} for name in names_list: d[name].append(10) The piece d[name] on the last line is how you would retrieve a value from a dictionary. It tries to retrieve the first name in the list, person_A, from the dictionary and throws a KeyError because that key doesn't exist. Did you mean to instead add a value to the dictionary? You would use the assignment operator, = # assigns the value 10 to eat name key names_list = ['person_A', 'person_B', 'person_C'] d = {} for name in names_list: d[name] = 10
2 of 3
2
in the first bit of code, the line rater_dict[name].append(rater_df) is actually telling python to fetch a preexisting value at key name (assumed to be a list) and add the dataframe to that list. since your dictionary starts off empty, python fails to find a value with that key and throws a KeyError, although this wouldn't give the desired behavior even if there was a list at that key. the syntax you want to use here is: rater_dict[name] = rater_df which creates the key name and stores the dataframe at that key. if you wanted to update it, at that point you could use rater_dict[name].append() to call pandas.DataFrame.append() . similarly, in the second bit of code, rater_dict={name:rater_df} sets the value of the dictionary itself to a single key-value pair of that one item, thus overriding the entire dictionary on each loop. that's why it only ends up with the last item, since all the previous ones were replaced.
🌐
Python.org
discuss.python.org › python help
Looping through Dictionary and add items to second dictionary - Python Help - Discussions on Python.org
September 25, 2022 - I am trying to loop through a dictionary and add values that satisfy my true statemen to a second dictionary At the moment, all I want to do is check and see if the value of each element is already a key in the entire dictionary and if so add it, otherwise go to next mydict={“John” : “House”, “Eric” : “Turtle”, “Jimmy” : “John”, “Charles” : “Eric”} myresult={“Jimmy” : “John”, “Charles” : Eric"} ← these two satisfy the true statement of the value being a key in the dictionary (i.e. value “Jo...
🌐
Python.org
discuss.python.org › python help
Add all loop values into dictionary - Python Help - Discussions on Python.org
June 23, 2023 - Hello again All…i really need help, spending time already. I have a code below, i want to add all loop values into dict. I tried but dont understand why only half is in the dict. Please help me fix…thanks ###Duplicate @ Y from collections import defaultdict import pandas as pd def dup_y(): df = pd.DataFrame( [ (76, 44), (32, 45), (77, 44), (78, 44), (78, 34), (78, 45), ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-add-items-to-dictionary-in-loop
Adding items to a Dictionary in a Loop in Python | bobbyhadz
Use a for loop to iterate over a sequence. Optionally, check if a certain condition is met. Use bracket notation to add items to the dictionary.
🌐
W3Schools
w3schools.com › python › python_dictionaries_loop.asp
Python - Loop Dictionaries
Remove List Duplicates Reverse ... Bootcamp Python Certificate Python Training ... You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, ...
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_dictionaries_add.asp
Python - Add Dictionary Items
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else · Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match ... Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range ... Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-add-items-to-dictionary-in-a-loop
How to Add Items to Dictionaries in Loops | Tutorial Reference
This guide covers how to efficiently add items to a dictionary within a loop in Python. We'll look at basic key-value insertion, handling potential duplicate keys, and building dictionaries where each key maps to a list of values. We'll use for loops, conditional logic, and the powerful collections.defaultdict for cleaner code.
🌐
Codecademy
codecademy.com › article › python-dictionary-append-how-to-add-items-to-dictionary
Python Dictionary Append: How to Add Items to Dictionary | Codecademy
Syntax of using a loop for adding items to a dictionary is: for key, value in some_iterable: dictionary[key] = value ... Ideal for bulk population from lists, files, APIs, etc. ... Now that you’ve seen different ways to add items to dictionaries ...
🌐
Delft Stack
delftstack.com › home › howto › python › python add to dictionary in loop
How to Add Key-Value Pairs to a Dictionary Within a Loop in Python | Delft Stack
February 2, 2024 - To add key-value pairs to a dictionary within a loop, we can create two lists that will store the keys and values of our dictionary. Next, assuming that the ith key is meant for the ith value, we can iterate over the two lists together and add ...
🌐
ProjectPro
projectpro.io › recipes › append-output-of-for-loop-dictionary
How to append output of a for loop in a dictionary in python -
December 22, 2022 - So this recipe is a short example on how to append output of for loop in a pandas dictionary. Let's get started. df= {'Table of 9': [9,18,27], 'Table of 10': [10,20,30]} Let us create a simple dataset of tables. for i in range(4,11): df['Table of 9'].append(i*9) df['Table of 10'].append(i*1) Append function on a particular list of dictionary helps in appending values.
🌐
Coding Rooms
codingrooms.com › blog › dictionary-with-for-loop-python
Python Dictionary with For Loop
List Comprehension is tough at first, because it feels unnatural, but the more you code in python, the more you will find the added benefits of using list comprehension. Just remember: Everything you do with list comprehension can be done with a for loop. But the inverse is not true. ... So how does this apply to the above problem? Well, below I show how we can use this new format to assist us! # Initialize the dictionary fruits = {'banana':3,'apple':2, 'mango':1, 'kiwi':5} # Create blank list to append to fruits_list = [[fruit]*quantity for fruit, quantity in fruits.items()] # Print out the final list print(fruits_list)
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-add-to-dictionary
How to Add and Update Python Dictionaries Easily | DigitalOcean
October 16, 2025 - Dictionaries are widely used in Python for various applications such as counting occurrences, grouping data, and storing configurations. Despite their versatility, there’s no built-in add method for dictionaries.
🌐
W3Schools
w3schools.com › python › gloss_python_loop_dictionary_items.asp
Python Loop Through a Dictionary
Print all key names in the dictionary, one by one: ... Python Dictionaries Tutorial Dictionary Access Dictionary Items Change Dictionary Item Check if Dictionary Item Exists Dictionary Length Add Dictionary Item Remove Dictionary Items Copy Dictionary Nested Dictionaries ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
Ars OpenForum
arstechnica.com › forums › operating systems & software › programmer's symposium
Add to nested dictionary within loop? (Python) | Ars OpenForum
July 7, 2022 - But it is now, and I'm getting useful data out of the dictionary, like dumping everything in the 'name' field into a list and converting it to a set, so I have unique values I can count occurrences of. ... I think it's also worth pointing out that your first loop is no longer needed. That loop is creating a load of empty dictionaries, then your second loop is overwriting those dictionaries with new ones that have your desired data already contained within. If counting is the task at hand then the Counter class might be of use too: https://docs.python.org/3/library/collections.html#collections.Counter
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › python: how to add items to dictionary
Python: How to Add Items to Dictionary
December 22, 2025 - The __setitem__ method is another way to add an item to a dictionary. The syntax is: ... The method sets the item key as "three" with the value 3. The ** operator merges an existing dictionary into a new dictionary and enables adding additional ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › append item to dictionary in python
Append Item to Dictionary in Python - Spark By {Examples}
May 31, 2024 - # Using ** operator append the ... 'fee': 4000, 'duration': '45 days'} Take specified key/value pairs as a list of tuples and then iterate each key/value pair using for loop....
🌐
Reddit
reddit.com › r/learnpython › append values to dictionary
r/learnpython on Reddit: Append values to Dictionary
June 8, 2021 -

I am currently using a while loop to loop and get certain values. I then want to append these values to a dictionary. Every loop through I want to append to two keys

General structure of the code: https://pastebin.com/p4hJcKR5

I have tried using:

dict[key] = value

dict.append(value)

And neither have worked, dict.append gives an error and dict[key] just sets the dictionary to the most recent iteration instead of iterating for all values. Any help would be appreciated.