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 pass statement
Python strptime()
Python vars()
Python slice()
Python String isdigit()
Python Program to Safely Create a Nested Directory
Python hex()
Python Directory and Files Management
Python Dictionary keys()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Capitalize the First Character of a String
Python Program to Return Multiple Values From a Function
Python String swapcase()
Python Program to Represent enum
Python Program to Parse a String to a Float or Int
Python Program to Print Hello world!
Python abs()
Python Program to Create a Countdown Timer
Python Program to Get the File Name From the File Path
Python Program to Convert Bytes to a String
Python globals()
Python callable()
Python String expandtabs()
Python Set difference_update()
Python String title()
Python Program to Check Armstrong Number
Python String rstrip()
Python Program to Find the Largest Among Three Numbers
Python Program to Slice Lists
Python Operator Overloading
Python Keywords and Identifiers
Python String isidentifier()