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()).

Answer from sberry on Stack Overflow
🌐
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.
Top answer
1 of 16
7025

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.

🌐
Real Python
realpython.com › iterate-through-dictionary-python
How to Iterate Through a Dictionary in Python – Real Python
November 23, 2024 - For Python dictionaries, .__iter__() allows direct iteration over the keys by default. This means that if you use a dictionary directly in a for loop, Python will automatically call .__iter__() on that dictionary, and you’ll get an iterator that goes over its keys:
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-dictionary-with-for-loop
Python Dictionary with For Loop - GeeksforGeeks
July 23, 2025 - In this code, we use the keys() method to obtain a view of the dictionary's keys, and then we iterate over these keys using a for loop.
🌐
freeCodeCamp
freecodecamp.org › news › dictionary-iteration-in-python
Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop
January 6, 2023 - How to Iterate through Dictionary Items with a for Loop · How to Loop through a Dictionary and Convert it to a List of Tuples ... With the Python for loop, you can loop through dictionary keys, values, or items. You can also loop through the ...
🌐
Python.org
discuss.python.org › python help
For Loop In a Dictionary - Python Help - Discussions on Python.org
June 16, 2022 - Hello guys, Please, how can I use a For Loop with Dictionary for this problem? This is what I have struggled with but getting three times the result. I want the result to lists all 10 stock prices for each stock. I also want to use a for loop to print out the stocks minimum price, average price, ...
🌐
Programiz
programiz.com › python-programming › examples › iterate-for-dictionary
Python Program to Iterate Over Dictionaries Using for Loop
As in Example 1, we can use iteritems() for python 2 versions. dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'} for key in dt.keys(): print(key) for value in dt.values(): print(value) ... You can use keys() and values() to explicitly return keys and values of the dictionary respectively.
🌐
Tutorialspoint
tutorialspoint.com › home › python › python loop through dictionaries
Python Loop Through Dictionaries
February 21, 2009 - The sequence can be a range of numbers, a list, a tuple, a string, or any iterable object. We can loop through dictionaries using a for loop in Python by iterating over the keys or key-value pairs within the dictionary.
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › looping-over-dictionaries
Looping over dictionaries - Python Morsels
March 6, 2023 - >>> counts = [('computers', 2), ('cats', 1), ('ducks', 3)] >>> for name, n in counts: ... print(n, name) ... 2 computers 1 cats 3 ducks · When you loop over a dictionary, you'll get keys. If you'd like to get keys and values, you can use the dictionary items method. But remember to ask yourself, why am I looping here and do I need a dictionary or would a list be a better way to store my data? ... We don't learn by reading or watching. We learn by doing. That means writing Python code.
🌐
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.
🌐
W3Schools
w3schools.com › python › gloss_python_loop_dictionary_items.asp
Python Loop Through a Dictionary
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. 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
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 10-4-conditionals-and-looping-in-dictionaries
10.4 Conditionals and looping in dictionaries - Introduction to Python Programming | OpenStax
March 13, 2024 - Looping in a dictionary can be done by iterating over keys or items. When looping using keys, keys are obtained using the keys() function and are passed to the loop variable one at a time.
🌐
SheCodes
shecodes.io › athena › 73172-creating-a-dictionary-using-a-for-loop-in-python
[Python] - Creating a Dictionary Using a For Loop in Python | SheCodes
Consider the following Python program. fin = open('words.txt') for line in fin: word = line.strip() print(word) What does the program loop over?
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to iterate over a dictionary in python ?
How to Iterate Over a Dictionary in Python? - Analytics Vidhya
February 7, 2025 - To do this, there are several commonly ... through all values. Use items() to iterate through key-value pairs. Employ a for loop to loop through the dictionary....
🌐
Python.org
discuss.python.org › python help
I need help understanding this code, it's a for loop inside a function and has to do with a dictionary - Python Help - Discussions on Python.org
January 25, 2023 - Hi, I’m new here and I’m doing my best to learn Python. Your help is much appreciated. I’m building a slot machine. The values in the dict. are the slot values." A" : 2 means there are two A’s “B” : 4 there are 4 B’s et…
🌐
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)
🌐
Note.nkmk.me
note.nkmk.me › home › python
Iterate Over Dictionary Keys, Values, and Items in Python | note.nkmk.me
April 24, 2025 - In Python, you can iterate over a dictionary (dict) using the keys(), values(), or items() methods in a for loop. You can also convert the keys, values, or items of a dictionary into a list using the ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-dictionary-in-python
Iterate over a dictionary in Python - GeeksforGeeks
July 11, 2025 - In Python, just looping through the dictionary provides you its keys. You can also iterate keys of a dictionary using built-in `.keys()` method. ... # create a python dictionary d = {"name": "Geeks", "topic": "dict", "task": "iterate"} # default loooping gives keys for keys in d: print(keys) # looping through keys for keys in d.keys(): print(keys)
🌐
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...
🌐
Geek University
geek-university.com › home › loop through a dictionary
Loop through a dictionary | Python#
March 18, 2022 - We then need to specify the name of the dictionary and use the items() method to return a list of key-value pairs. ... my_dict = {'eye_color': 'blue', 'height': '165cm', 'weight': '54kg'} for k,v in my_dict.items(): print('The key is:',k,'and the value is:',v) Inside the for loop we’ve defined the k and v variables that will be used for each key (the variable k) and value (the variable v) in the iterations.