key is just a variable name.

Use with AIfor 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:

Use with AIfor key, value in d.items():

For Python 2.x:

Use with AIfor 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
7030

key is just a variable name.

Use with AIfor 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:

Use with AIfor key, value in d.items():

For Python 2.x:

Use with AIfor 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
569

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

    Use with AIfor k in dict: ...
    

    which is equivalent to, but much faster than

    Use with AIfor 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:

    Use with AIfor 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.

Discussions

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
For Loop In a Dictionary
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, ... More on discuss.python.org
🌐 discuss.python.org
4
0
June 16, 2022
Build Dictionary in Python Loop - List and Dictionary Comprehensions - Stack Overflow
and then I recently discovered ... (is there a name for this type of loop? I'd really like to know so I can search on it a little better): ... Ok, that being said, I wanted to go further with the last type of loop and I tried to build a python dictionary using the same type ... More on stackoverflow.com
🌐 stackoverflow.com
Populating a dictionary using two for loops in Python - Stack Overflow
I'm trying to create a dictionary using two for loops. Here is my code: dicts = {} keys = range(4) values = ["Hi", "I", "am", "John"] for i in keys: for ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Kansas State University
textbooks.cs.ksu.edu › intro-python › 08-dictionaries › 03-loops-dictionaries
Loops with Dictionaries :: Introduction to Python
July 30, 2026 - However, the dictionary will only store the key for each key-value pair in the iterator variable. So, to access the value associated with the key, we can simply place it in square brackets after the dictionary’s variable name. When we run this program, we should see the following output: As we can see, it will print each key-value pair in the dictionary, one per line. The other method we can use when looping through a dictionary allows us to access both the keys and values directly within the loop.
🌐
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.
🌐
Python Morsels
pythonmorsels.com › looping-over-dictionaries
Looping over dictionaries - Python Morsels
August 27, 2026 - >>> counts = [('computers', 2), ... 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? Now make sure you remember what you just watched: Daily Recall shows you a few Python questions ...
🌐
Real Python
realpython.com › iterate-through-dictionary-python
How to Iterate Through a Dictionary in Python – Real Python
September 9, 2025 - 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:
Find elsewhere
🌐
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 ...
🌐
Medium
medium.com › @python-javascript-php-html-css › comprehending-dictionary-iteration-in-python-using-for-loops-a4f89429e702
Comprehending Dictionary Iteration in Python using ‘for’ Loops
September 29, 2024 - This process might seem straightforward, but it raises questions about how Python interprets the elements within the loop, especially the role of variables like ‘key’. To clarify, ‘key’ in a ‘for’ loop is not a special keyword but simply a variable that takes on each key in the dictionary during iteration.
🌐
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 values() method is employed in the for loop to iterate through each value in the dictionary. Inside the loop, we print a statement that incorporates the current price. By utilizing values(), you can efficiently traverse through all the values of the dictionary, making it particularly useful when your task involves working with the values directly rather than the associated keys. This method enhances the flexibility of dictionary manipulation in Python.
🌐
SitePoint
sitepoint.com › python hub › loop dictionaries
Python - Loop Dictionaries | SitePoint — SitePoint
There are several ways for looping through dictionaries: ... If you use a dictionary in a for statement, it traverses the keys of the dictionary. This behavior is both intuitive and efficient, as keys are often the primary points of reference ...
🌐
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 Training ... You can loop through a dictionary by using a for loop.
🌐
Reddit
reddit.com › r/learnpython › what is the fastest way to iterate over a dictionary?
r/learnpython on Reddit: What is the fastest way to iterate over a dictionary?
January 4, 2023 -

I was iterating over a dictionary, (more specifically a Counter object) and only needed the values, so I did something like: "for vals in dictName.values():"

However, I got a relatively slow runtime and was trying out different things, and then I tried: "for key, vals in dictName.items()" and the runtime was halved.

So, my question is: Why is one way faster than the other? And how is it working internally?

If someone can shed some light or point me in the direction of documentation explaining this speedup, I would be grateful. Thank you

Top answer
1 of 10
36
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
2 of 10
29
Could you post your code? That seems very surprising - if there was a difference at all, I'd expect it to be .items() that was slower, since it's bringing back more stuff and has to build a tuple. Some quick timing seems to bear this out: d={k:k for k in range(1000)} %timeit list(d.items()) 24.6 µs ± 311 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) %timeit list(d.values()) 5.81 µs ± 17.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In fact, items() seems significantly slower than I'd expect. I also tried with a for loop rather than using list to exhaust in case that was introducing something, and the results aren't as big, but in the same direction: %timeit for x in d.values(): pass 10.2 µs ± 1.22 µs per loop (mean ± std. dev. of 7 runs, 100,000 loops each) %timeit for x in d.items(): pass 18.3 µs ± 96.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) So items is nearly twice as slow (I suspect the main difference between this and the list() test is the proportion of other code involved: we only see such an effect because we're doing virtually nothing, so the proportion involved is much larger than it'd be in a real program. As such, I suspect you're doing something wrong, and my first guess to what that is would be to check: are you actually iterating through the returned object. Ie. if you're just timing the .items() call, you're not checking the right thing, since these are lazy - they just return a view on the object and won't do any iteration until you actually start reading from the iterator. As such, they'll just take a constant time unrelated to the size of your dict etc, and unrepresentative of what happens when you iterate.
🌐
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, ...
🌐
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 ...
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › python › python_loop_dictionaries.htm
Python - Loop Dictionaries
The for loop iterates over each key in the view object, allowing you to perform operations based on the keys of the dictionary during each iteration − · student = {"name": "Alice", "age": 21, "major": "Computer Science"} # Looping through ...
🌐
Stack Overflow
stackoverflow.com › questions › 30280856 › populating-a-dictionary-using-two-for-loops-in-python
Populating a dictionary using two for loops in Python - Stack Overflow
I'm trying to create a dictionary using two for loops. Here is my code: dicts = {} keys = range(4) values = ["Hi", "I", "am", "John"] for i in keys: for ...
🌐
Quora
quora.com › In-Python-what-decides-the-order-that-a-loop-on-a-dictionary-works-through-the-keys
In Python, what decides the order that a loop on a dictionary works through the keys? - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
Coursera
coursera.org › home › categories › information technology › support and operations
Crash Course on Python: Write and Debug Python Programs | Coursera
September 21, 2020 - You'll also explore common errors when using for loops and how to fix them. ... In this module you'll dive into more advanced ways to manipulate strings using indexing, slicing, and advanced formatting. You'll also explore the more advanced data types: lists, tuples, and dictionaries.
Rating: 4.8 ​ - ​ 40.6K votes