Different ways to Iterate / Loop over a Dictionary in Python
In this article we will discuss different ways to iterate over a dictionary
Suppose we have a dictionary with string as key and integers as value i.e.
''' Creating Dictionaries with string as key and int as value ''' wordFrequency = { "Hello" : 7, "hi" : 10, "there" : 45, "at" : 23, "this" : 77 }
Now let’s see how to iterate over this dictionary using 2 different techniques i.e.
Iterate over the dictionary using for loop over keys | “for in dictionary”
By using for in dictionary, it loops through all the keys in dictionary and for each key select the value and prints it.
''' Iterate over the dictionary using for loop ''' for key in wordFrequency: value = wordFrequency[key] print(key, " :: ", value)
Output:
Hello :: 7 there :: 45 at :: 23 this :: 77 hi :: 10
Its not an efficient solution because we are iterating over all the keys in dictionary and for each key we are again searching for its associated value.
Let’s see an efficient method i.e.
Iterate over key value pairs of dictionary using dict.items()
dict.items()
It returns a iterable View object of all key,value elements in the dictionary. Its backed by original dictionary.
Let’s iterate over the list using dict.iter() i.e.
''' Iterate over the dictionary using items() ''' for key , value in wordFrequency.items(): print(key, " :: ", value)
Output:
Hello :: 7 there :: 45 at :: 23 this :: 77 hi :: 10
As, view object is backed by original dictionary, therefore any changes made in dictionary will be reflected in it.
For example,
Take a view object of dictionary i.e.
# Take a dictionary view dictView = wordFrequency.items()
View object is,
dict_items([('this', 77), ('hi', 10), ('Hello', 7), ('there', 45), ('at', 23)])
Now modify the dictionary
wordFrequency["hi"] = 90
Now same view object will also be modified because its backed by original dictionary
dict_items([('this', 77), ('hi', 90), ('Hello', 7), ('there', 45), ('at', 23)])
Python Dictionary Tutorial - Series:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- Merge two or more dictionaries in python
Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.
Complete example is as follows,
def main(): ''' Creating Dictionaries with string as key and int as value ''' wordFrequency = { "Hello" : 7, "hi" : 10, "there" : 45, "at" : 23, "this" : 77 } ''' Iterate over the dictionary using for loop ''' for key in wordFrequency: value = wordFrequency[key] print(key, " :: ", value) print("**************") ''' Iterate over the dictionary using items() ''' for key , value in wordFrequency.items(): print(key, " :: ", value) # Take a dictionary view dictView = wordFrequency.items() print("Dictionary View before modification : ", dictView, sep ="\n") # Modify the dictionary wordFrequency["hi"] = 90 print("Dictionary View after modification : ", dictView, sep ="\n") if __name__ == "__main__": main()
Output:
there :: 45 hi :: 10 this :: 77 at :: 23 Hello :: 7 ************** there :: 45 hi :: 10 this :: 77 at :: 23 Hello :: 7 Dictionary View before modification : dict_items([('there', 45), ('hi', 10), ('this', 77), ('at', 23), ('Hello', 7)]) Dictionary View after modification : dict_items([('there', 45), ('hi', 90), ('this', 77), ('at', 23), ('Hello', 7)])
Leave a Reply