Python: Iterate over dictionaries using for loops
5. Iterate Over Dictionary Using For Loops
Write a Python program to iterate over dictionaries using for loops.
Sample Solution:
Python Code:
# Create a dictionary 'd' with key-value pairs.
d = {'x': 10, 'y': 20, 'z': 30}
# Iterate through the key-value pairs in the dictionary using a for loop.
# 'dict_key' represents the key, and 'dict_value' represents the value for each pair.
for dict_key, dict_value in d.items():
# Print the key followed by '->' and the corresponding value.
print(dict_key, '->', dict_value)
Sample Output:
x -> 10 y -> 20 z -> 30
For more Practice: Solve these Related Problems:
- Write a Python program to iterate over a dictionary and print each key and its corresponding value.
- Write a Python program to iterate over a dictionary's items using the items() method and display them in a formatted table.
- Write a Python program to use a for-loop to iterate over dictionary keys and access values using bracket notation.
- Write a Python program to iterate over a dictionary and calculate the sum of all its numeric values.
Go to:
Previous: Write a Python program to check if a given key already exists in a dictionary.
Next: Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.