# 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 Answer from RiceKrispyPooHead on reddit.com
🌐
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.
Discussions

python 3.x - How to add key and value pairs to new empty dictionary using for loop? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
python - Adding item to Dictionary within loop - Stack Overflow
Below data is grasped from webpage and containing entries as below(like a table with many rows): entry1: key1: value1-1, key2: value2-1, key3: value3-1 entry2: key1: value1-2, key2: value2-2, key3: More on stackoverflow.com
🌐 stackoverflow.com
Looping through Dictionary and add items to second dictionary
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” : ... More on discuss.python.org
🌐 discuss.python.org
7
0
September 25, 2022
python - Iterating over a dictionary using a 'for' loop, getting keys - Stack Overflow
A pair of braces creates an empty ... braces adds initial key:value pairs to the dictionary. No, key is not a special word in Python. Here key is Just a variable name. ... Keys are immutable data types. Keys are unique. ... "Is key a special keyword, or is it simply a variable?" There are no such "special keywords" for for loop ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - The time and space complexity of the above solution is the same as the previous solution’s, O(n). The above two code snippets use a for loop. We can perform the same task using a while loop. The following code snippet depicts adding values to a dictionary using a while loop. def print_dictionary(dictionary): for key, value in dictionary.items(): print(f"{key}: {value}") class Point: def __init__(self, x, y): self.x = x self.y = y def add(*args): s = 0 for x in args: s += x return s dictionary = {} keys = [ "Integer", "String", "Float", "List of Strings", "List of Float Numbers", "List of Int
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]
🌐
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 ...
🌐
datagy
datagy.io › home › python posts › python: add key:value pair to dictionary
Python: Add Key:Value Pair to Dictionary • datagy
December 19, 2022 - # Loop Over Two Lists to Create a Dictionary keys = ['Nik', 'Kate', 'Jane'] values = [32, 31, 30] dictionary = {} for i in range(len(keys)): dictionary[keys[i]] = values[i] print(dictionary) # Returns: {'Nik': 32, 'Kate': 31, 'Jane': 30} Here, we loop over each value from 0 through to the length of the list minus 1, to access the indices of our lists. We then access the ith index of each list and assign them to the keys and values of our lists. There is actually a much simpler way to do this – using the Python zip function, which you’ll learn about in the next section.
🌐
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...
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-add-items-to-dictionary-in-loop
Adding items to a Dictionary in a Loop in Python | bobbyhadz
April 9, 2024 - 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. ... Copied!my_list = [ ('first', 'bobby'), ('last', 'hadz'), ('site', 'bobbyhadz.com') ] my_dict ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python add keys to dictionary
Python Add keys to Dictionary - Spark By {Examples}
May 31, 2024 - Python provides several ways to add new keys to a dictionary. Dictionaries are data type in python, that allows you to store key-value pairs. To add keys
🌐
W3Schools
w3schools.com › python › python_dictionaries_loop.asp
Python - Loop Dictionaries
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp 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, but there are methods to return the values as well.
Top answer
1 of 16
7027

key is just a variable name.

Copyfor key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 3.x:

Copyfor key, value in d.items():

For Python 2.x:

Copyfor key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

2 of 16
567

It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, e.g. see this question for how to build class iterators.

In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":

  • Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write

    Copyfor k in dict: ...
    

    which is equivalent to, but much faster than

    Copyfor k in dict.keys(): ...
    

    as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

  • Add methods to dictionaries that return different kinds of iterators explicitly:

    Copyfor key in dict.iterkeys(): ...
    
    for value in dict.itervalues(): ...
    
    for key, value in dict.iteritems(): ...
    

    This means that for x in dict is shorthand for for x in dict.iterkeys().

In Python 3, dict.iterkeys(), dict.itervalues() and dict.iteritems() are no longer supported. Use dict.keys(), dict.values() and dict.items() instead.

🌐
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(): ...
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › python: how to add items to dictionary
Python: How to Add Items to Dictionary
April 1, 2026 - If the provided key exists, the existing key value is not updated, and the dictionary remains unchanged. Add key-value pairs to a nested list and loop through the list to add multiple items to a dictionary.
🌐
Stack Overflow
stackoverflow.com › questions › 71039013 › loop-through-python-dictionary-and-add-different-values-with-same-keys-to-a-new
Loop through Python dictionary and add different values with same keys to a new dictionary - Stack Overflow
for key, value in student_scores.items(): if (value > 90) student_grades[key] = "Excellent" else student_grades[key] = "Okey-ish" ... Sign up to request clarification or add additional context in comments. ... Thanks Aziz, I did the loop as you advised and migrated all the grades to a new dictionary with new values successfully. Thanks a lot! 2022-02-08T18:41:01.053Z+00:00 ... 0 Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats
🌐
py4u
py4u.org › blog › python-trying-to-create-a-dictionary-through-a-for-loop
How to Create a Python Dictionary Using a For Loop: Mapping List Values to Ordered Keys
When creating dictionaries, for loops let you: Dynamically assign keys and values based on list elements. Handle complex logic (e.g., filtering values, transforming data) during dictionary creation.
🌐
W3Schools
w3schools.com › python › gloss_python_loop_dictionary_items.asp
Python Loop Through a Dictionary
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp 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, but there are methods to return the values as well.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Iterate Over Dictionary Keys, Values, and Items in Python | note.nkmk.me
April 24, 2025 - To iterate over dictionary key-value pairs, use the items() method. Built-in Types - dict.items() — Python 3.13.3 documentation · for k, v in d.items(): print(k, v) # key1 1 # key2 2 # key3 3 ... You can also receive the key-value pairs as ...