- How do you Loop Through a Dictionary in Python?
- Defining Dictionary in Python
- Syntax
- Method 1: Iterate using for Loop
- Example
- Output
- Method 2: Iterate using items()
- Example
- Output
- Method 3: Iterate using keys()
- Example
- Output
- Method 4: Iterate using values()
- Example
- Output
- Conclusion
- Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop
- What We’ll Cover
- How to Iterate through a Dictionary with a for Loop
- How to Iterate through Dictionary Keys with a for Loop
- How to Iterate through Dictionary Values with a for Loop
- How to Iterate through Dictionary Items with a for Loop
- How to Loop through a Dictionary and Convert it to a List of Tuples
- Conclusion
- How to Loop through Python Dictionary?
- Examples
- 1. Iterate through items of given dictionary
- 2. Loop through keys in given dictionary
- 3. Loop through values in given dictionary
- 4. Loop through key:value pairs in given dictionary
- Summary
How do you Loop Through a Dictionary in Python?
Python, the programming language and one of the most popular object-oriented programming languages, was built around dictionaries. Dictionaries are described as written maps of multiple objects. Python dictionaries let you organize data in a flexible way, storing key-value pairs in an elaborate structure and accessing them by the same name.
Looking for different ways to traverse through a dictionary? This guide is perfect for you. It covers the use of a for loop, items(), keys(), and value() functions to loop over a dictionary. And, it also contains an illustrative example demonstrating each of these approaches in action.
But before digging into how Python iterates through dictionaries, let’s see what’s the structure of a dictionary in Python.
Defining Dictionary in Python
When working with dictionaries in Python, one must take into account the following considerations −
- Dictionaries map keys to their corresponding values and arrange them as an organized array.
- The keys need to be immutable − that is, possessing an unchanging hash value throughout their lifespan.
As of now, we know that the dictionary stores data in a key-value format. This means that every value is assigned a unique key that can be used to reference that particular value.
Syntax
Let’s have a look at the syntax below,
A dictionary is constructed by wrapping a set of key-value combinations within braces (<>), with the values being separated by commas. A dictionary in Python makes use of a colon(:) to separate the keys and values. Here d is defined for the dictionary.
Now consider you want to create a program for a machine that shows a specific laptop’s brand, windows version, processor, and other related information. To implement, you need to iterate through the dictionary storing that data so you can display it to the user of your program.
Have a look at an example of a dictionary in Python −
The words on the left of the colons are considered keys. In our example, company, windows_version, and processor are keys.
Method 1: Iterate using for Loop
Dictionaries, being iterable objects, can be worked with in the same way as any other. Looping through a dictionary using a for loop is one of the most straightforward methods to do this; this method lets you access each value of the dictionary in turn.
Let’s say you are writing a program for a laptop. You want to print out the keys and values of a specific laptop to the console and each key-value pair should be printed to the console on a new line. How will you accomplish this?
Example
Well, bring the following code into the picture and witness the magic!
laptop = < 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', >for key in laptop: print(key, laptopLoop through dictionary python)
Output
Our code returns the output as −
company HP windows_version 11 processor Intel Core i7
- We have initiated a variable called laptop that contains three pairs of keys and values.
- This has been expressed using the dictionary data type.
- To showcase this information, we initiate a for loop that cycles through each value and displays both the key as well as its corresponding value to the console.
Method 2: Iterate using items()
With dictionary.items(), we can convert all the key-value pairs of a dictionary into a tuple. We can employ the use of a for loop along with the items() method to iterate through all the content in the list
Example
Let’s use our laptop dictionary as an example. To display our values in the form of a list of tuples, we could use the following code snippet
laptop = < 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', >for i in laptop.items(): print(i)
Output
Our code returns a list of tuples −
('company', 'HP') ('windows_version', '11') ('processor', 'Intel Core i7')
- With a for loop, we have traversed our laptop dictionary by employing items().
- Each key-value pair will be transformed into a tuple, which we can then use inside the for loop.
- Observe how every single pair was printed to the console in the form of tuples. If you want to access every value in your dictionary as a tuple while iterating over it, this method can prove to be beneficial.
Method 3: Iterate using keys()
Suppose, our boss is interested in the information that the online store stores about its laptops, and we need to generate a list of the keys stored in our dictionary. To achieve this goal, Python provides us with the handy keys() method that can extract all keys from a given dictionary.
Example
To do so, here’s how our code should look −
laptop = < 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', >for k in laptop.keys(): print(k)
Output
company windows_version processor
- To illustrate, we’ve established a for loop to pinpoint the keys stored in our dictionary.
- Every key is iterated through and printed on the screen, displaying the three designated keys as a result.
Method 4: Iterate using values()
To access the values stored in a Python dictionary, one can use the values() method. Unlike keys(), this function iterates over and returns each value present within the dictionary.
Example
An example of this is illustrated in the following code −
laptop = < 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', >for v in laptop.values(): print(v)
Output
- We have initiated the for loop to print the values stored in our dictionary.
- Values are iterated through, printed on the screen, and displayed as the result.
Conclusion
And there you are! In this article, we explore several efficient methods for iterating through a dictionary in Python. We also implement each method in code. You’re now ready to start iterating through Python dictionaries without scratching your head!
Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop
Kolade Chris
In Python, a dictionary is one of the built-in data structures (the others are tuples, lists, and sets). A dictionary is a collection of key:value pairs and you can use them to solve various programming problems.
Dictionaries are very flexible to work with. You can get the keys and values separately, or even together.
This article is about looping over a dictionary with the for loop, but you can also loop through a dictionary with three methods:
- the key() method: gets you the keys in a dictionary
- the values() method: gets you the values in a dictionary
- the items() method: gets you both the keys and values in a dictionary
In the example below, I use those 3 methods to get the keys, values, and items of the dictionary.
states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' ># Keys states_keys = states_tz_dict.keys() print(states_keys) # dict_keys(['Florida', 'Hawaii', 'Arizona', 'Colorado', 'Idaho', 'Texas', 'Washington', 'Wisconsin']) # Values tz_values = states_tz_dict.values() print(tz_values) # dict_values(['EST and CST', 'HST', 'DST', 'MST', 'MST and PST', 'CST and MST', 'PST', 'CST']) # Keys and values states_tz_dict_items = states_tz_dict.items() print(states_tz_dict_items) # dict_items([('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')])
That’s some iterations we did. But you can also loop through a dictionary with a for loop. That’s what we are going to look at in this tutorial.
What We’ll Cover
How to Iterate through a Dictionary with a for Loop
With the Python for loop, you can loop through dictionary keys, values, or items. You can also loop through the dictionary and put the key:value pair in a list of tuples. We are going to look at them one by one.
How to Iterate through Dictionary Keys with a for Loop
Remember how I got the keys of the dictionary with the keys() method in the first part of this article? You can use the same method in a for loop and assign each of the keys to a variable we can call k :
states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k in states_tz_dict.keys(): print(k) # Result: # Florida # Hawaii # Arizona # Colorado # Idaho # Texas # Washington # Wisconsin
How to Iterate through Dictionary Values with a for Loop
You can use the values() method in a for loop too, and assign the values to a variable you can call v :
states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for v in states_tz_dict.values(): print(v) # Result: # EST and CST # HST # DST # MST # MST and PST # CST and MST # PST # CST
How to Iterate through Dictionary Items with a for Loop
The items() method comes in handy in getting the keys and values inside a for loop. This time around, you have to assign two variables instead of one:
states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k, v in states_tz_dict.items(): print(k,"--->", v) # Result: # Florida ---> EST and CST # Hawaii ---> HST # Arizona ---> DST # Colorado ---> MST # Idaho ---> MST and PST # Texas ---> CST and MST # Washington ---> PST # Wisconsin ---> CST
Note: You can use any letter for the variable(s) in a for loop. It doesn’t have to be k or v, or k, v.
How to Loop through a Dictionary and Convert it to a List of Tuples
To convert a dictionary to a list of tuples in Python, you still have to use the items() method inside a for loop.
But this time around, you have to surround the loop with square brackets. You also have to assign the loop to a separate variable and wrap the variable for both keys and values in brackets:
states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >list_of_tuples = [(k, v) for k, v in states_tz_dict.items()] print(list_of_tuples) # Result: [('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST # and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')]
Conclusion
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.
If you find this article helpful, don’t hesitate to share it on social media.
Kolade Chris
Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
How to Loop through Python Dictionary?
Dictionary is a collection of items. Each item is a key:value pair. And all the items in a dictionary can be traversed using a looping statement or traversing technique.
To loop through a dictionary, we can use Python for loop. In this tutorial, we will learn how to iterate through key:value pairs of dictionary, or just the keys or just the values.
Examples
1. Iterate through items of given dictionary
In this example, we will initialize a dictionary with three key:value pairs. We shall use Python For Loop to iterate over this dictionary, and print the keys.
Python Program
myDictionary = < "name": "Lini", "year": 1989, "expertise": "data analytics">#iterate through dictionary for key in myDictionary: print(key, '-', myDictionaryLoop through dictionary python)
name - Lini year - 1989 expertise - data analytics
All the keys are printed by traversing through the Python dictionary using for loop. And during each iteration, we could access the value corresponding to a key using indexing.
2. Loop through keys in given dictionary
To traverse exclusively through keys, you can use the default for item in iterable statement as shown below.
Python Program
myDictionary = < "name": "Lini", "year": 1989, "expertise": "data analytics">#iterate through dictionary for key in myDictionary: print(key)
3. Loop through values in given dictionary
To traverse exclusively through values, you can use the default for item in iterable statement as shown below.
Python Program
myDictionary = < "name": "Lini", "year": 1989, "expertise": "data analytics">#iterate through dictionary values for value in myDictionary.values(): print(value)
In the above example, we have used dict.values(). dict.values() returns iterator over only the values in the dictionary.
4. Loop through key:value pairs in given dictionary
Or you can use for loop, to access both key and value, as shown below.
Python Program
myDictionary = < "name": "Lini", "year": 1989, "expertise": "data analytics">#iterate through key:value pairs of dictionary for key, value in myDictionary.items(): print(key, ': ', value)
myDictionary.items() returns an iterator that provides access to both key and value.
name : Lini year : 1989 expertise : data analytics
Summary
In this tutorial of Python Examples, we learned how to traverse through the Dictionary items using for loop with the help of well detailed examples.