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
The 10 Best Scholarship Websites To Find Money For College
How To Make $300 Fast In One Week - Passive Income Wise
UPS Paketshop: Filialen & Standorte
Dte Outage Map Woodhaven
Polyhaven Hdri
2022 Apple Trade P36
Routing Number 041203824
Shaniki Hernandez Cam
AB Solutions Portal | Login
Strange World Showtimes Near Amc Braintree 10
Lima Crime Stoppers
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
OSRS Dryness Calculator - GEGCalculators
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Quest Beyondtrustcloud.com
Price Of Gas At Sam's
History of Osceola County
Craigslist Free Stuff Merced Ca
Tinker Repo
Robin D Bullock Family Photos
Isaidup
Best Transmission Service Margate
Craigslist Battle Ground Washington
Sandals Travel Agent Login
3569 Vineyard Ave NE, Grand Rapids, MI 49525 - MLS 24048144 - Coldwell Banker
208000 Yen To Usd
Vivification Harry Potter
Calvin Coolidge: Life in Brief | Miller Center
Ezstub Cross Country
Datingscout Wantmatures
All Things Algebra Unit 3 Homework 2 Answer Key
How to Watch the X Trilogy Starring Mia Goth in Chronological Order
Log in or sign up to view
11 Pm Pst
What Time Is First Light Tomorrow Morning
Dr. John Mathews Jr., MD – Fairfax, VA | Internal Medicine on Doximity
5 Tips To Throw A Fun Halloween Party For Adults
Mvnt Merchant Services
Ferguson Employee Pipeline
Gt500 Forums
O'reilly's Palmyra Missouri
Engr 2300 Osu
Emily Browning Fansite
فیلم گارد ساحلی زیرنویس فارسی بدون سانسور تاینی موویز
Advance Auto.parts Near Me
Craigslist/Nashville
Ucla Basketball Bruinzone
Noga Funeral Home Obituaries
Craigslist Marshfield Mo
Quest Diagnostics Mt Morris Appointment
Gelato 47 Allbud
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.