Home > Article > Backend Development > How to loop through a dictionary in Python?
Python is a programming language and one of the most popular object-oriented programming languages that is built around dictionaries. A dictionary is described as a written mapping of multiple objects. Python dictionaries allow you to organize your data in a flexible way, storing key-value pairs in complex structures and accessing them by the same name.
Looking for a different way to iterate over a dictionary? This guide is for you. It covers looping over dictionaries using for loops, items(), keys(), and value() functions. Furthermore, it includes an illustrative example that demonstrates each method in action.
But before we delve into how Python iterates over dictionaries, let’s first see what the structure of a dictionary is in Python.
When using dictionaries in Python, you must consider the following considerations -
Dictionaries map keys to corresponding values and arrange them into organized arrays.
The key must be immutable - that is, have an unchanged hash value throughout its lifetime.
So far, we know that dictionaries store data in key-value format. This means that each value is assigned a unique key that can be used to reference that specific value.
Let’s take a look at the syntax below,
d = { <key>: <value>, <key>: <value>, . . . <key>: <value> }
A dictionary is constructed by enclosing a set of key-value combinations in curly braces ({}), with values separated by commas. Dictionaries in Python use colon (:) to separate keys and values. Here d is defined for the dictionary.
Now consider that you want to create a program for a machine that displays a specific laptop's brand, Windows version, processor, and other relevant information. To achieve this, you need to iterate over the dictionary that stores this data so you can display it to the user of your program.
Look at the dictionary example in Python -
laptop = { 'company': ‘HP', 'windows_version': '11', ‘processor': Intel Core i7, }
The words to the left of the colon are considered keys. In our example, company, windows_version, and processor are the keys.
Dictionaries are iterable objects and can be used like any other object. Using a for loop to iterate over a dictionary is one of the simplest methods; this method allows you to access each value of the dictionary in turn.
Suppose you are writing a program for a laptop. You want to print 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 achieve this?
Then, put the following code into the picture and witness the miracle!
laptop = { 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', } for key in laptop: print(key, laptop[key])
The output returned by our code is -
company HP windows_version 11 processor Intel Core i7
We started a variable called "laptop" which contains three pairs of keys and values.
This has been represented using the dictionary data type.
To display this information, we start a for loop that loops through each value and displays the key and its corresponding value to the console.
Using dictionary.items(), we can convert all key-value pairs of the dictionary into tuples. We can use a for loop and the items() method to iterate over everything in the list
Let’s take the laptop dictionary as an example. To display our values as a list of tuples we can use the following code snippet
laptop = { 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', } for i in laptop.items(): print(i)
Our code returns a list of tuples -
('company', 'HP') ('windows_version', '11') ('processor', 'Intel Core i7')
Through the for loop, we iterated through the laptop dictionary using items().
Each key-value pair will be converted into a tuple, which we can then use in a for loop.
Observe how each pair is printed to the console as a tuple. This method may be useful if you want to access each value in the dictionary as a tuple while iterating.
Suppose our boss is interested in the information stored by an online store about his laptop, and we need to generate a list of keys stored in a dictionary. To achieve this goal, Python provides us with the convenient keys() method, which can extract all keys from a given dictionary.
For this our code should look like this -
laptop = { 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', } for k in laptop.keys(): print(k)
Our code returns -
company windows_version processor
To illustrate this, we set up a for loop to pinpoint the keys stored in the dictionary.
Each key will be iterated and printed on the screen, with the results showing the three specified keys.
To access values stored in a Python dictionary, you can use the values() method. Unlike keys(), this function iterates and returns each value present in the dictionary.
The following code illustrates an example -
laptop = { 'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7', } for v in laptop.values(): print(v)
Our code returns -
HP 11 Intel Core i7
We have started a for loop to print the values stored in the dictionary.
Values are iterated, printed on the screen and displayed as the result.
You are right here! In this article, we explored several efficient ways to iterate over dictionaries in Python. We also implemented each method in the code. You're now ready to start iterating over Python dictionaries without breaking a sweat!
The above is the detailed content of How to loop through a dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!