Open In App

Iterate over a dictionary in Python

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover How to Iterate Through a Dictionary in Python. Dictionary in Python is a collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair in Python

To Iterate through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys.

Python Dictionaries

Dictionaries in Python are very useful data structures. Dictionaries store items in key-value pairs.

Dictionary keys are hashable type, meaning their values don’t change in a lifetime. There can not be duplicate keys in a dictionary.

To access the value stored in a Python dictionary you have to use keys.

How to Iterate Through a Dictionary in Python

Iterating through a dictionary means, visiting each key-value pair in order. It means accessing a Python dictionary and traversing each key-value present in the dictionary. Iterating a dictionary is a very important task if you want to properly use a dictionary.

There are multiple ways to iterate through a dictionary, we are discussing some generally used methods for dictionary iteration in Python which are the following:

  • Iterate Python dictionary using build.keys() 
  • Iterate through all values using .values()
  • Looping through Python Dictionary using for loop
  • Iterate key-value pair using items()
  • Access key Using map() and dict.get
  • Access key in Python Using zip()
  • Access key Using Unpacking of Dict

Note: In Python version 3.6 and earlier, dictionaries were unordered. But since Python version 3.7 and later, dictionaries are ordered.

Iterating Dictionary in Python using .values() method

To iterate through all values of a dictionary in Python using .values(), you can employ a for loop, accessing each value sequentially. This method allows you to process or display each individual value in the dictionary without explicitly referencing the corresponding keys.

Example: In this example, we are using the values() method to print all the values present in the dictionary.

Python3




# create a python dictionary
statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
print('List Of given capitals:\n')
 
for capital in statesAndCapitals.values():
    print(capital)


Output:

List Of given capitals:
Gandhinagar
Mumbai
Jaipur
Patna

Access Dictionary keys in Python Using the build .keys() 

In Python, accessing the keys of a dictionary can be done using the built-in `.keys()` method. It returns a view object that displays a list of all the keys in the dictionary. This view can be used directly or converted into a list for further manipulation.

Example: In this example, the below code retrieves all keys from the `statesAndCapitals` dictionary using `.keys()` and prints the resulting view object.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
keys = statesAndCapitals.keys()
print(keys)


Output:

dict_keys(['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar'])

Looping through Python Dictionary using for loop

To access keys in a dictionary without using the `keys()` method, you can directly iterate over the dictionary using a for loop, like `for key in my_dict:`. This loop automatically iterates over the keys, allowing you to access each key directly without the need for an explicit method call.

Example: In this example, we are Iterating over dictionaries using ‘for’ loops for iterating our keys and printing all the keys present in the Dictionary.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
print('List Of given states:\n')
 
# Iterating over keys
for state in statesAndCapitals:
    print(state)


Output:

List Of given states:
Gujarat
Maharashtra
Rajasthan
Bihar

Iterate through a dictionary using items() method

You can use the built-in items() method to access both keys and items at the same time. items() method returns the view object that contains the key-value pair as tuples. 

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
 
for key, value in statesAndCapitals.items():
    print(f"{key}: {value}")


Output:

Gujarat: Gandhinagar
Maharashtra: Mumbai
Rajasthan: Jaipur
Bihar: Patna

Iterating Python Dictionary Using map() and dict.get

The method accesses keys in a dictionary using `map()` and `dict.get()`. It applies the `dict.get` function to each key, returning a map object of corresponding values. This allows direct iteration over the dictionary keys, efficiently obtaining their values in a concise manner.

Example: In this example, the below code uses the `map()` function to create an iterable of values obtained by applying the `get` method to each key in the `statesAndCapitals` dictionary. It then iterates through this iterable using a `for` loop and prints each key.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
map_keys = map(statesAndCapitals.get, statesAndCapitals)
for key in map_keys:
    print(key)


Output :

Gandhinagar
Mumbai
Jaipur
Patna

Iterate Python Dictionary using zip() Function

Using `zip()` in Python, you can access the keys of a dictionary by iterating over a tuple of the dictionary’s keys and values simultaneously. This method creates pairs of keys and values, allowing concise iteration over both elements.

Example: In this example, the zip() function pairs each state with its corresponding capital, and the loop iterates over these pairs to print the information

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
for state, capital in zip(statesAndCapitals.keys(), statesAndCapitals.values()):
    print(f'The capital of {state} is {capital}')


Output :

The capital of Gujarat is Gandhinagar
The capital of Maharashtra is Mumbai
The capital of Rajasthan is Jaipur
The capital of Bihar is Patna

Dictionary iteration in Python by unpacking the dictionary

To access keys using unpacking of a dictionary, you can use the asterisk (*) operator to unpack the keys into a list or another iterable.

Example: In this example, you will see that we are using * to unpack the dictionary. The *dict method helps us to unpack all the keys in the dictionary.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
keys = [*statesAndCapitals]
values = '{Gujarat}-{Maharashtra}-{Rajasthan}-{Bihar}'.format(*statesAndCapitals, **statesAndCapitals)
print(keys)
print(values)


Output:

['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar']
Gandhinagar-Mumbai-Jaipur-Patna

Iterating through the dictionary is an important task if you want to access the keys and values of the dictionary. In this tutorial, we have mentioned several ways to iterate through all items of a dictionary. Important methods like values(), items(), and keys() are mentioned along with other techniques.



Previous Article
Next Article

Similar Reads

Python - How to Iterate over nested dictionary ?
In this article, we will discuss how to iterate over a nested dictionary in Python. Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. Nested dictionary in use: {'Student 1': {'Name': 'Bobby', 'Id': 1, 'Age': 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, 'Age':
3 min read
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print(dictionary_name[index][i] Example: Python Code #
2 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over the characters of a string in Python. Example #1: Using simple iteration and range() C/C++ Code # Python program to iterate over characters of a string # Code #1 string_name = "geeksforgeeks" # Iterate over the string for el
3 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
three90RightbarBannerImg