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

🌐
W3Schools
w3schools.com › python › python_dictionaries_loop.asp
Python - Loop Dictionaries
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 ...
Discussions

Iterate through a Dictionary
loop over both at once using .items() for key,value in ngrams.items(): More on reddit.com
🌐 r/learnpython
14
1
September 10, 2019
How does Python iterate over dictionary keys in a 'for' loop? - TestMu AI Community
How does Python recognize that it needs only to read the key from the dictionary when using a ‘for’ loop to python iterate over dictionary? In the following code: d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(k… More on community.testmuai.com
🌐 community.testmuai.com
0
November 10, 2024
Why do you need to apply the method .items() to iterate over a dictionary?
Do you think that iterating over a dictionary should iterate over the keys, the values, or the keys and values together? This was discussed and decided that iterating over a dictionary should iterate over the keys only. So you very much CAN do: for key in data_dict: print(key) It's only if you want the values or the values and keys together that you need an extra method. for key, value in data_dict.items(): print(key, 'is linked to', value) More on reddit.com
🌐 r/learnpython
5
4
November 18, 2020
What is the fastest way to iterate over a dictionary?
try again but this time do "for key, vals in dictName.items()" first and "for vals in dictName.values():" second see if your times still hold More on reddit.com
🌐 r/learnpython
17
99
January 4, 2023
🌐
Real Python
realpython.com › iterate-through-dictionary-python
How to Iterate Through a Dictionary in Python – Real Python
November 23, 2024 - This is the primary way to iterate through a dictionary in Python. You just need to put the dictionary directly into a for loop, and you’re done! If you use this approach along with the [key] operator, then you can access the values of your dictionary while you loop through the keys:
🌐
GeeksforGeeks
geeksforgeeks.org › python › iterate-over-a-dictionary-in-python
Iterate over a dictionary in Python - GeeksforGeeks
July 11, 2025 - There are multiple ways to iterate through a dictionary, depending if you need key, value or both key-value pairs. To iterate through all values of a dictionary in Python using .values(), you can employ a for loop, accessing each value sequentially.
🌐
Reddit
reddit.com › r/learnpython › iterate through a dictionary
r/learnpython on Reddit: Iterate through a Dictionary
September 10, 2019 -

I’m stumped on how to iterate through a dictionary and compare each keys value to one another. I’m able to compare the first key value to the rest of the keys in the dictionary but after that, comparing say the third key to the first key all in the same loop seems impossible to me as of now.

I’m sure it all goes in a loop starting with:

for keys in ngrams.keys():

basically I’m trying to pull the keys with values who equal the highest (simplified version) and grab those two keys from the rest.

Any tips would be appreciated!

🌐
Note.nkmk.me
note.nkmk.me › home › python
Iterate Over Dictionary Keys, Values, and Items in Python | note.nkmk.me
April 24, 2025 - The values() method returns dict_values, which can be converted to a list using list(). print(d.values()) # dict_values([1, 2, 3]) print(type(d.values())) # <class 'dict_values'> ... To iterate over dictionary key-value pairs, use the items() method.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to iterate over keys and values in python dictionaries
How To Iterate Over Keys and Values in Python Dictionaries | Towards Data Science
January 19, 2025 - Now in case you need to iterate over both keys and values in one go, you can call [items()](https://docs.python.org/3/library/stdtypes.html#dict.items). The method will return a tuple containing the key value pairs in the form (key, value).
Find elsewhere
🌐
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 - The keys() method is utilized in the for loop to iterate through each key (fruit) in the dictionary. Inside the loop, we access the corresponding value using the key and print the fruit along with its price.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-iterate-dictionary-key-value
Python Iterate Dictionary Key, Value - GeeksforGeeks
July 23, 2025 - #function to iterate over each keys and its #corresponding values def dict_iter(d): for i in d: print('KEYS: {} and VALUES: {}'.format(i,d[i])) #Main Function if __name__ == &quot;__main__&quot;: d = {&quot;Vishu&quot;:1,&quot;Aayush&quot;:2,&quot;Neeraj&quot;:3,&quot;Sumit&quot;:4} #calling function created above dict_iter(d) ... KEYS: Vishu and VALUES: 1 KEYS: Aayush and VALUES: 2 KEYS: Neeraj and VALUES: 3 KEYS: Sumit and VALUES: 4 · In this example we will be using Python's dictionary function .items() .
🌐
freeCodeCamp
freecodecamp.org › news › python-iterate-over-dictionary-how-to-loop-through-a-dict
Python Iterate Over Dictionary – How to Loop Through a Dict
March 10, 2023 - In general, using a basic for loop to iterate through the keys of a dictionary is the fastest method of looping through a dictionary in Python. This is because it avoids the overhead of creating a list of the dictionary's keys or items. The items() method is slower than a basic for loop because it creates a new list of tuples that contains the key-value pairs of the dictionary.
🌐
Sentry
sentry.io › sentry answers › python › iterate over a dictionary in python
Iterate over a dictionary in Python | Sentry
January 30, 2023 - The simplest way to iterate over a Python dictionary is to iterate over its keys. The following code will print each key in a dictionary with its corresponding value:
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python iterate over a dictionary
Python Iterate Over A Dictionary - Spark By {Examples} %
May 31, 2024 - So, the loop effectively iterates over the keys of the technology dictionary and prints each key along with its associated value. This is a common and concise way to access both keys and values in a dictionary using a for loop. # Use key to get the Value technology={"Course":"python","Fee":4000,"Duration":"60 days"} for key in technology: print(key,technology[key])
🌐
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 - In this tutorial, we looked at how to iterate through a dictionary with the for loop. If you don’t want to use a for loop, you can also use any of the keys(), values(), or items() methods directly like I did in the first part of this article.
🌐
Quantifiedcode
docs.quantifiedcode.com › python-anti-patterns › readability › not_using_items_to_iterate_over_a_dictionary.html
Not using items() to iterate over a dictionary — Python Anti-Patterns documentation
PEP 20 states “There should be one– and preferably only one –obvious way to do it.” The preferred way to iterate over the key-value pairs of a dictionary is to declare two variables in a for loop, and then call dictionary.items(), where dictionary is the name of your variable representing ...
🌐
TestMu AI Community
community.testmuai.com › ask a question
How does Python iterate over dictionary keys in a 'for' loop? - TestMu AI Community
November 10, 2024 - How does Python recognize that it needs only to read the key from the dictionary when using a ‘for’ loop to python iterate over dictionary? In the following code: d = {'x': 1, 'y': 2, 'z': 3} for key in d: print(k…
🌐
Wscube Tech
wscubetech.com › home › how to iterate through a dictionary in python? (with examples)
How to Iterate Through a Dictionary in Python? (With Examples)
October 21, 2024 - Using the built-in items() method in Python, we can access keys and items at the same time, so we can effectively manipulate the entire structure of the dictionary. This powerful tool allows us to iterate through key-value pairs and returns ...
🌐
iO Flood
ioflood.com › blog › iterate-a-dictionary-in-python-guide-with-examples
Iterate a Dictionary in Python: Guide (With Examples)
January 31, 2024 - Iterating through a Python dictionary involves looping over its keys and values. The basic method is to use a for loop. For example, for key in dictionary: print(key, dictionary[key]). This will print each key and its corresponding value.
🌐
Career Karma
careerkarma.com › blog › python › iterate through dictionary python: step-by-step guide
Iterate Through Dictionary Python: Step-By-Step Guide | Career Karma
December 1, 2023 - The words on the left of the colons ... as strings. You can iterate through a Python dictionary using the keys(), items(), and values() methods....
🌐
Educative
educative.io › answers › how-to-iterate-over-a-dictionary-in-python
How to iterate over a dictionary in Python
The fastest way to iterate over a dictionary in Python is using the items() method, which returns both keys and values in each iteration, avoiding extra lookups.
🌐
W3Schools
w3schools.com › python › gloss_python_loop_dictionary_items.asp
Python Loop Through a Dictionary
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.