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 Trim Whitespace From a String
Python Program to Add Two Numbers
Python String upper()
Python Program to Convert String to Datetime
Python String split()
Python List remove()
Python Program to Get the Last Element of the List
Python frozenset()
Python String capitalize()
Python Namespace and Scope
Python String rpartition()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Sets
Python Program to Print all Prime Numbers in an Interval
Python oct()
Python if...else Statement
Python Program to Merge Mails
Python Program Read a File Line by Line Into a List
Python Global, Local and Nonlocal variables
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Dictionary clear()
Python Program to Access Index of a List Using for Loop
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Shallow Copy and Deep Copy
Python String casefold()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python List Comprehension
Python List extend()
Python bool()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Tuple index()
Python Program to Find Armstrong Number in an Interval