Iterate over a dictionary in Python
Last Updated :
22 Nov, 2024
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop 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.
How to Loop Through a Dictionary in Python
There are multiple ways to iterate through a dictionary, depending if you need key, value or both key-value pairs.
Iterate through Value
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.
Python
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# loop over dict values
for val in d.values():
print(val)
Iterate through keys
In Python, just looping through the dictionary provides you its keys. You can also iterate keys of a dictionary using built-in `.keys()` method.
Python
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# default loooping gives keys
for keys in d:
print(keys)
# looping through keys
for keys in d.keys():
print(keys)
Iterate through both keys and values
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.
Python
# create a python dictionary
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}
# iterating both key and values
for key, value in d.items():
print(f"{key}: {value}")
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.
Python
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
Python
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.
Python
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.
Similar Reads
Python Program to Swap dictionary item's position
Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best':
4 min read
Merging or Concatenating two Dictionaries in Python
Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into
2 min read
How to Compare Two Dictionaries in Python
In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator. Using == operatorThis operator checks if both dictionaries have the same keys and values. [GFGTABS] Python d1 = {'a': 1, 'b
2 min read
Python Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable} Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are ite
4 min read
How to Add Values to Dictionary in Python
The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Add new keys to a dictionary in Python
In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
2 min read
Add Item after Given Key in Dictionary - Python
The task of adding an item after a specific key in a Pythondictionary involves modifying the order of the dictionary's key-value pairs. Since Python dictionaries maintain the insertion order, we can achieve this by carefully placing the new key-value pair after the target key. For example, consider
4 min read
Python - Ways to remove a key from dictionary
We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}. Using pop()pop() method removes a specific key from the dictionary and returns its co
3 min read
Removing Dictionary from List of Dictionaries - Python
We are given a list of dictionaries, and our task is to remove specific dictionaries based on a condition. For instance given the list: a = [{'x': 10, 'y': 20}, {'x': 30, 'y': 40}, {'x': 50, 'y': 60}], we might want to remove the dictionary where 'x' equals 30 then the output will be [{'x': 10, 'y':
3 min read
Python - Remove item from dictionary when key is unknown
We are given a dictionary we need to remove the item or the value of key which is unknown. For example, we are given a dictionary a = {'a': 10, 'b': 20, 'c': 30} we need to remove the key 'b' so that the output dictionary becomes like {'a': 10, 'c': 30} . To do this we can use various method and app
4 min read