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
key
andvalue
for iterabledt.items()
.items()
returns thekey:value
pairs. - Print
key
andvalue
.
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
key
and 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 Program to Transpose a Matrix
Python staticmethod()
Python Program to Find the Sum of Natural Numbers
Python String endswith()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python next()
Python String isprintable()
Python getattr()
Python Set issubset()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python List count()
Python Program to Measure the Elapsed Time in Python
Python String istitle()
Python Object Oriented Programming
Python Program to Slice Lists
Python Program to Find Factorial of Number Using Recursion
Python Program to Extract Extension From the File Name
Python Dictionary values()
Python Set difference_update()
Python File I/O Operation
Python Program to Print all Prime Numbers in an Interval
Python Recursion
Python Program to Parse a String to a Float or Int
Python Program to Merge Mails
Python Program to Check Prime Number
Python isinstance()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Sets
Python Program to Add Two Numbers
Python Program to Represent enum
Python Modules
Python Program to Concatenate Two Lists