[toc]
Introduction
A Python dictionary stores data in the form of key-value pairs. A dictionary in Python is
- ordered,
- mutable and
- does not allow duplicates.
The keys in the dictionary are paired with the values by using a colon (:) while the commas fill in as a separator for the pairs. The values can be the same but the keys have to be unique in a dictionary.
✒️Note: Since Python 3.7, dictionaries are ordered. However, in Python3.6 and earlier, dictionaries are unordered.
Example:
names_and_countries = {'Chris': 'Germany', 'Beth': 'Bulgaria', 'Rashi': 'India', 'Dani': 'Denmark', 'Shubham': 'Australia'}
Recommended Tutorial: Python Dictionary – The Ultimate Guide
Now that you have an idea about the dictionary data structure in Python, let us dive into our mission-critical question – “How to iterate over the elements in a Python dictionary?”
❖ Problem Formulation
You have been given a dictionary and asked to recover a particular key or value from this dictionary. How would you do this? To do this, you have to iterate over the dictionary to extract a particular data. Thus, in this tutorial, we will see how to iterate over a Dictionary.
Example:
# Given a dictionary d = {"Book": "To Kill a Mockingbird", "Author": "Harper Lee", "Date": 1960} print("Dictionary: ", d) # Iterating over the dictionary using for loop for key in d: print(key, ':', d[key])
Output:
Dictionary: {'Book': 'To Kill a Mockingbird', 'Author': 'Harper Lee', 'Date': 1960} Book : To Kill a Mockingbird Author : Harper Lee Date : 1960
Now without any further ado, let’s dive into the methods to iterate over a dictionary.
✨Method 1: Using a “For” Loop
In Python, you can a dictionary object can be treated as an iterable object. Thus, you can easily iterate over the keys of the dictionary using a “for
” loop. You can simply use the square-bracket notation, i.e., dict[key]
during the iteration to access the value associated with a key in the dictionary.
Let’s have a look at an example to understand this.
d = {"Book": "To Kill a Mockingbird", "Author": "Harper Lee", "Date": 1960} print("Dictionary: ", d) print() # Iterating over the dictionary using for loop print("Iterating over Keys and Values:") for key in d: print(key, ':', d[key]) print() # Iterating and accessing the values print("Accessing Values:") for key in d: print(d[key])
Output:
Dictionary: {'Book': 'To Kill a Mockingbird', 'Author': 'Harper Lee', 'Date': 1960} Iterating over Keys and Values: Book : To Kill a Mockingbird Author : Harper Lee Date : 1960 Accessing Values: To Kill a Mockingbird Harper Lee 1960
Discussion: In this approach, the dictionary object has been used as an iterator to iterate over the keys of the dictionary and the values associated with each key. This is certainly not an efficient solution since we are iterating over keys first and later accessing the value associated with them. We could have straightforwardly iterated over all the values of the dictionary. This method is however beneficial when you want to access both the key and the value associated with it from the dictionary.
✨Method 2: Using items()
Python provides a function items()
that returns an iterable/view consisting of a sequence of all key-value pairs of the dictionary as tuples in a list.
Note: When the value of an item in the dictionary is changed, the view object also gets updated.
Syntax:
dictionary.items() |
- You can use the
items()
method alongside a “for
” loop to iterate over all the key-value pairs in the dictionary.
Example
# Given a dictionary d = {"Book": "To Kill a Mockingbird", "Author": "Harper Lee", "Date": 1960} print("Dictionary: ", d) print() print("Key-value pairs:") # Iterating over the dictionary using items() for item in d.items(): print(item) print() # Iterating using key and Value for key, item in d.items(): print(key, ":", item)
Output:
Dictionary: {'Book': 'To Kill a Mockingbird', 'Author': 'Harper Lee', 'Date': 1960} Key-value pairs: ('Book', 'To Kill a Mockingbird') ('Author', 'Harper Lee') ('Date', 1960) Book : To Kill a Mockingbird Author : Harper Lee Date : 1960
✨Method 3: Using keys()
You can iterate over a dictionary using its keys using the keys()
method.
keys()
is an inbuilt method in Python that extracts the keys present in a dictionary and stores them in a list. It returns a view object that contains the keys of the dictionary in a list.
Syntax:
dictionary.keys() |
Example:
d = {"Book": "To Kill a Mockingbird", "Author": "Harper Lee", "Date": 1960} print("Given Dictionary: ", d) # Iterating over the dictionary using keys() for key in d.keys(): print(key)
Output:
Given Dictionary: {'Book': 'To Kill a Mockingbird', 'Author': 'Harper Lee', 'Date': 1960} Book Author Date
This method is particularly useful when you need to access the keys of the dictionary.
✨Method 4: Using values()
This method is similar to the previous approach with the only difference being that instead of iterating with the help of keys we will iterate through the values in the dictionary.
values()
is a built-in method in Python that returns a view object. This view object consists of the values of the dictionary, stored in a list.
Syntax: dictionary.values()
Example:
d = {"Book": "To Kill a Mockingbird", "Author": "Harper Lee", "Date": 1960} print("Given Dictionary: ", d) # Iterating over the dictionary using values() for value in d.values(): print(value)
Output:
Given Dictionary: {'Book': 'To Kill a Mockingbird', 'Author': 'Harper Lee', 'Date': 1960} To Kill a Mockingbird Harper Lee 1960
This method is particularly useful when you need to access the values of the dictionary.
TRIVIA
A Python dictionary uses a data structure known as a hashmap. The key in a dictionary gets converted with the help of a hash algorithm from a string (or whatever) into an integer value, and it involves a couple of very simple calculations to use that integer value and search the right place in the dictionary to look.
Conclusion
We have discussed numerous methods to iterate over a dictionary in Python in this tutorial. I hope it helped you.? Please stay tuned and subscribe for more interesting solutions and articles!
Related Article: How To Iterate Over A Python Dictionary In Random Order?
✍ Post Credits: Shubham Sayon and Rashi Agarwal
- Do you want to master the most popular Python IDE fast?
- This course will take you from beginner to expert in PyCharm in ~90 minutes.
- For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!