Python: Iterate over dictionaries using for loops
9. Iterate Over Dictionaries (Alternative)
Write a Python program to iterate over dictionaries using for loops.
Sample Solution:
Python Code:
# Create a dictionary 'd' with color names as keys and corresponding numerical values as values.
d = {'Red': 1, 'Green': 2, 'Blue': 3}
# Iterate through the key-value pairs in the dictionary 'd' using a for loop.
for color_key, value in d.items():
# Print the color name, 'corresponds to', and its corresponding numerical value.
print(color_key, 'corresponds to ', d[color_key])
Sample Output:
Red corresponds to 1 Green corresponds to 2 Blue corresponds to 3
For more Practice: Solve these Related Problems:
- Write a Python program to iterate over a dictionary using a for-loop and print each key, value, and index.
- Write a Python program to loop through a dictionary and display its keys sorted in alphabetical order.
- Write a Python program to use dictionary comprehension to iterate and create a new dictionary with modified values.
- Write a Python program to iterate over a dictionary's keys and values using nested loops to print a formatted output.
Python Code Editor:
Previous: Write a Python script to merge two Python dictionaries.
Next: Write a Python program to sum all the items in a dictionary.
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