
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do you Loop Through a Dictionary in Python?
What is 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,
d = { <key>: <value>, <key>: <value>, . . . <key>: <value> }
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 −
laptop = { 'company': ‘HP', 'windows_version': '11', ‘processor': Intel Core i7, }
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, laptop[key])
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
Our code returns −
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
Our code returns −
HP 11 Intel Core i7
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!
- Related Articles
- How do you loop through a C# array?
- Loop through a Dictionary in Javascript
- How to iterate through a dictionary in Python?
- Do you think a Python dictionary is thread safe?
- How do I loop through a JSON file with multiple keys/sub-keys in Python?
- Do you think Python Dictionary is really Mutable?
- How to emulate a do-while loop in Python?
- How to loop through multiple lists using Python?
- How do we define dictionary in Python?
- How do we loop through array of arrays containing objects in JavaScript?
- How do Python Dictionary Searching works?
- How do you throw an Exception without breaking a for loop in java?
- How do you use a ‘for loop’ for accessing array elements in C#?
- How do Python dictionary hash lookups work?
- How do I format a string using a dictionary in Python 3?
