Table of Contents
In this example, you will learn to iterate over dictionaries using for loop.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Access both key and value using items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
print(key, value)
Output
a juice b grill c corn
- Using a for loop, pass two loop variables
keyandvaluefor iterabledt.items().items()returns thekey:valuepairs. - Print
keyandvalue.
2. Example 2: Access both key and value without using items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt:
print(key, dt[key])
Output
a juice b grill c corn
- Iterate through the dictionary using a for loop.
- Print the loop variable
keyand value atkey(i.e.dt[key]).
However, the more pythonic way is example 1.
3. Example 3: Access both key and value using iteritems()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.iteritems():
print(key, value)
Output
a juice b grill c corn
It works for python 2 versions.
As in Example 1, we can use iteritems() for python 2 versions.
4. Example 4: Return keys or values explicitly
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt.keys():
print(key)
for value in dt.values():
print(value)
Output
a b c juice grill corn
You can use keys() and values() to explicitly return keys and values of the dictionary respectively.
Related posts:
Python format()
Python input()
Python Package
Python Anonymous / Lambda Function
Python File I/O Operation
Python ord()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Get File Creation and Modification Date
Python Program to Calculate the Area of a Triangle
Python String partition()
Python issubclass()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python print()
Python Shallow Copy and Deep Copy
Python Program to Get Line Count of a File
Python Matrices and NumPy Arrays
Python slice()
Python Program to Count the Number of Each Vowel
Python String title()
Python Program to Get a Substring of a String
Python Program to Create Pyramid Patterns
Python Generators
Python String index()
Python Variables, Constants and Literals
Python Set clear()
Python String encode()
Python zip()
Python oct()
Python Program to Compute the Power of a Number
Python divmod()
Python staticmethod()