Iterate over a dictionary in Python - GeeksforGeeks (2024)

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.

Python
# 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.

Python
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.

Python
statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'}print('List Of given states:\n')# Iterating over keysfor 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.

Python
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.

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.

Iterate over a dictionary in Python – FAQs

How can we iterate over keys in a Python dictionary?

To iterate over keys in a Python dictionary, you can use the keys() method or directly iterate over the dictionary. Here are both methods:

# Example dictionary
my_dict = {'a': 1, 'b': 2,, 'c': 3}

# Using the keys() method
for key in my_dict.keys():
print(key)

# Directly iterating over the dictionary
for key in my_dict:
print(key)

Both methods will output:

a
b
c

How to access values while iterating over a Python dictionary?

To access values while iterating over a dictionary, you can use the key to get the corresponding value:

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
value = my_dict[key]
print(f"Key: {key}, Value: {value}")

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

What method is used to iterate over both keys and values in Python?

The items() method allows you to iterate over both keys and values in a dictionary. It returns a view object that displays a list of a dictionary’s key-value tuple pairs.

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

How to modify values during iteration in a Python dictionary?

To modify values during iteration, you can directly assign new values to the keys in the dictionary:

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
my_dict[key] += 1

print(my_dict)

Output:

{'a': 2, 'b': 3, 'c': 4}

Are there any Python modules that enhance dictionary iteration?

Yes, there are Python modules and functions that can enhance dictionary iteration. One such module is collections, which provides additional data structures like defaultdict and OrderedDict. Additionally, tools from the itertools module can be useful.

Using defaultdict from collections:

from collections import defaultdict

# Example defaultdict
my_dict = defaultdict(int, {'a': 1, 'b': 2, 'c': 3})

for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")

Using OrderedDict from collections:

from collections import OrderedDict

# Example OrderedDict
my_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])

for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

Using itertools for advanced iteration:

import itertools

# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Iterating with itertools
for key, value in itertools.zip_longest(my_dict.keys(), my_dict.values()):
print(f"Key: {key}, Value: {value}")



R

rituraj_jain

Iterate over a dictionary in Python - GeeksforGeeks (1)

Improve

Previous Article

Why is iterating over a dictionary slow in Python?

Next Article

Python - How to Iterate over nested dictionary ?

Please Login to comment...

Iterate over a dictionary in Python - GeeksforGeeks (2024)
Top Articles
🇦🇲 Flag: Armenia Emoji
The Most Common Electric Scooter Issues and How to Fix Them
Access-A-Ride – ACCESS NYC
CLI Book 3: Cisco Secure Firewall ASA VPN CLI Configuration Guide, 9.22 - General VPN Parameters [Cisco Secure Firewall ASA]
Algebra Calculator Mathway
Google Sites Classroom 6X
Kobold Beast Tribe Guide and Rewards
Top 10: Die besten italienischen Restaurants in Wien - Falstaff
Wausau Marketplace
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
35105N Sap 5 50 W Nit
Samsung 9C8
13 The Musical Common Sense Media
fltimes.com | Finger Lakes Times
Walmart Windshield Wiper Blades
My.tcctrack
2020 Military Pay Charts – Officer & Enlisted Pay Scales (3.1% Raise)
R Personalfinance
Effingham Bookings Florence Sc
Drago Funeral Home & Cremation Services Obituaries
Craigslist Maui Garage Sale
How to Watch the Fifty Shades Trilogy and Rom-Coms
Selfservice Bright Lending
Culver's Flavor Of The Day Taylor Dr
Bella Bodhi [Model] - Bio, Height, Body Stats, Family, Career and Net Worth 
12 Top-Rated Things to Do in Muskegon, MI
Great Clips Grandview Station Marion Reviews
Finding Safety Data Sheets
Lovindabooty
SOGo Groupware - Rechenzentrum Universität Osnabrück
Lbrands Login Aces
Waters Funeral Home Vandalia Obituaries
Cinema | Düsseldorfer Filmkunstkinos
Big Boobs Indian Photos
Pipa Mountain Hot Pot渝味晓宇重庆老火锅 Menu
Angel del Villar Net Worth | Wife
The Mad Merchant Wow
Whitehall Preparatory And Fitness Academy Calendar
Empire Visionworks The Crossings Clifton Park Photos
Craigslist Pets Huntsville Alabama
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
Saybyebugs At Walmart
Infinite Campus Farmingdale
Martha's Vineyard – Travel guide at Wikivoyage
Southwest Airlines Departures Atlanta
The Average Amount of Calories in a Poke Bowl | Grubby's Poke
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Google Flights Missoula
Compete My Workforce
Jovan Pulitzer Telegram
Subdomain Finer
How to Choose Where to Study Abroad
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5817

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.