Algorithm
1. Initialize the dictionary.
2. Use a for loop to iterate over the items of the dictionary.
3. Inside the loop, access the current key-value pair using loop variables.
4. Perform desired operations using the key and value within the loop.
5. Continue the loop until all key-value pairs have been processed.
Code Examples
#1 Code Example- Access both key and value using items()
Code -
Python Programming
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.items():
print(key, value)
Copy The Code &
Try With Live Editor
Output
b grill
c corn
#2 Code Example- Access both key and value without using items()
Code -
Python Programming
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt:
print(key, dt[key])
Copy The Code &
Try With Live Editor
Output
b grill
c corn
#3 Code Example- Access both key and value using iteritems()
Code -
Python Programming
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key, value in dt.iteritems():
print(key, value)
Copy The Code &
Try With Live Editor
Output
b grill
c corn
#4 Code Example- Return keys or values explicitly
Code -
Python Programming
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
for key in dt.keys():
print(key)
for value in dt.values():
print(value)
Copy The Code &
Try With Live Editor
Output
b
c
juice
grill
corn
Demonstration
Python Programimg Example to Iterate Over Dictionaries Using for Loop-DevsEnv