How to iterate through dictionaries using for in Python

April 2, 2022

How to iterate through dictionaries using for in Python

In this article you will learn how to iterate through dictionaries using for – so that you can access each item in your Python dictionary running a loop.

iterate through dictionaries thumb

Hey you all guys, OK? Let’s learn more about dictionaries and Python on this article!

Basically the dictionary is a set of keys and values, which in other languages is represented by an associative array.

And also the Python dictionary has a structure very close to the object in JavaScript

That said, how to access a dictionary running a “for” command reading your keys and values

Very simple! Let’s use the items method and make a “for” loop. Let’s see the practical example:

parts = {
 'doors': 2,
 'windows': 4,
 'engine': 1,
 'tires': 4

for key, value in parts.items():
 print(key, ' => ', value)

The output for this expression will be:

doors => 2
windows => 4
engine => 1
tires => 4

See how simple it is, we just create two temporary variables, which are: key and value

The key represents the key of the dictionary values, and the value will represent all the values of each key, got that?

That way you can access the keys and values, or just what you want for your program logic


In this article we learned  how to iterate in dictionaries using for in Python language

It is very interesting because the items method gives us access to the items and also keys to the dictionary, just creating the temporary variables in the for instance

Do you want to learn more about Python? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x