Python: Iterate over dictionaries 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
Python Code Editor:
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).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics