Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds
There are multiple ways to iterate over a dictionary in Python.
- Iterate through all keys
- Iterate through all values
- Iterate through all key, value pairs
Iterate through all keys:
The order of states in the below code will change every time because the dictionary doesn’t store keys in a particular order.
List Of given states: Rajasthan Bihar Maharashtra Gujarat
In order to maintain the order of keys and values in a dictionary, use OrderedDict.
List Of given states: Gujarat Maharashtra Rajasthan Bihar
Above dictionary is an OrderedDict as the keys and values are stored in the order in which they were defined in the dictionary. Hence the above method should be used when we want to maintain the order of (key, value) stored in the dictionary.
Iterate through all values:
Again, in this case, the order in which the capitals are printed in the below code will change every time because the dictionary doesn’t store them in a particular order.
List Of given capitals: Gandhinagar Jaipur Mumbai Patna
Iterate through all key, value pairs:
List Of given states and their capitals: Bihar : Patna Gujarat : Gandhinagar Rajasthan : Jaipur Maharashtra : Mumbai
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python Iterate over multiple lists simultaneously
- Iterate over a set in Python
- Iterate over characters of a string in Python
- Iterate over words of a String in Python
- Python - Iterate over Columns in NumPy
- Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
- How to Iterate over Dataframe Groups in Python-Pandas?
- Iterate over a list in Python
- Different ways to iterate over rows in Pandas Dataframe
- How to iterate over rows in Pandas Dataframe
- How to iterate over the keys and values with ng-repeat in AngularJS ?
- How to iterate over filtered (ng-repeat filter) collection of objects in AngularJS ?
- How to iterate over an Array using for loop in Golang?
- Java Program to Iterate Over Arrays Using for and foreach Loop
- Python | Iterate through value lists dictionary
- Python | Ways to iterate tuple list of lists
- Python - Iterate through list without using the increment variable
- Iterate associative array using foreach loop in PHP
- How to iterate through all selected elements into an array ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.