You're looking for Python Dictionaries.

sample = {}
for i in range(6):
   # some code that gives you x
   sample[i] = x
print(sample)

Do note, however, that since your keys are just 0, 1, 2 etc., you may want to just use a list instead:

sample = []
for i in range(6):
    # some code that gives you x
    sample.append(x)
print(sample)

Note that dictionary access using sample[key] will look identical to list access using sample[index] since you're just using consecutive numeric keys.

Answer from brunston on Stack Overflow
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › add-a-keyvalue-pair-to-dictionary-in-python
Add a key value pair to Dictionary in Python - GeeksforGeeks
For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'for'}, we add multiple key-value pairs at once: 'key3': 'Geeks', 'key4': 'is', 'key5': 'portal', and 'key6': 'Computer'.
Published   July 11, 2025
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python add keys to dictionary
Python Add keys to Dictionary - Spark By {Examples}
May 31, 2024 - You can create a new dictionary from an iterable object like a list, and specify the key-value pairs using a simple expression. You can then merge this new dictionary with an existing dictionary using the unpacking operator **. Adding new keys ...
🌐
YouTube
youtube.com › watch
Python Dictionary : add key value pair to dictionary python | #pythondictionary #dictionarymethods - YouTube
python add keys to dictionary, how to add values to dictionary in python, how to add values in dictionary in python using loop, how to add values to dictiona...
Published   October 15, 2023
🌐
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 ...
🌐
DataCamp
datacamp.com › tutorial › python-dictionary-append
Python Dictionary Append: How to Add Key-Value Pairs | DataCamp
August 6, 2024 - Appending elements to a dictionary ... The most straightforward way to add a single key-value pair to a dictionary is using square bracket notation....
Find elsewhere
🌐
datagy
datagy.io › home › python posts › python: add key:value pair to dictionary
Python: Add Key:Value Pair to Dictionary • datagy
December 19, 2022 - 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. The Python zip() function allows us to iterate over two iterables sequentially. This saves us having to use an awkward range() function to access the indices of items in the lists. ... # Loop Over Two Lists to Create a Dictionary using Zip keys = ['Nik', 'Kate', 'Jane'] values = [32, 31, 30] dictionary = {} for key, value in zip(keys, values): dictionary[key] = value print(dictionary) # Returns: {'Nik': 32, 'Kate': 31, 'Jane': 30}
🌐
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 ...
🌐
W3Schools
w3schools.com › python › python_dictionaries_loop.asp
Python - Loop Dictionaries
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python 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, but there are methods to return the values as well.
🌐
TutorialsPoint
tutorialspoint.com › add-a-key-value-pair-to-dictionary-in-python
Add a key value pair to dictionary in Python
CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34} print(CountryCodeDict) CountryCodeDict.update( {'Germany' : 49} ) print(CountryCodeDict) # Adding multiple key value pairs CountryCodeDict.update( [('Austria', 43),('Russia',7)] ) print(CountryCodeDict) Running the above code gives us the following result ? {'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44} {'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44} {'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7, 'Spain': 34} We can also append elements to a dictionary by merging two dictionaries.
🌐
Analytics Vidhya
analyticsvidhya.com › home › 5 methods to add new keys to a dictionary in python
5 Methods to Add New Keys to a Dictionary in Python
February 7, 2025 - Several methods are available in Python to add new keys to a dictionary. Let’s explore each of these methods in detail. One of the simplest ways to add a new key-value pair to a dictionary is by using the bracket notation.
🌐
Sanfoundry
sanfoundry.com › python-program-add-key-value-pair-dictionary
Python Program to Add a Key-Value Pair to the Dictionary - Sanfoundry
May 30, 2022 - 2. Declare a dictionary and initialize it to an empty dictionary. 3. Use the update() function to add the key-value pair to the dictionary. 4. Print the final dictionary. 5. Exit.
🌐
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....
Top answer
1 of 16
7024

key is just a variable name.

for 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:

for key, value in d.items():

For Python 2.x:

for 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

    for k in dict: ...
    

    which is equivalent to, but much faster than

    for 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:

    for 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.

Top answer
1 of 16
4456

You create a new key/value pair on a dictionary by assigning a value to that key

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.

2 of 16
1364

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

Inserting/Updating a single value

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

This uses a new feature called dictionary unpacking.

data = {**data1, **data2, **data3}

Python 3.9+:

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))