Python: Iterate over dictionaries using for loops

Python dictionary: Exercise-9 with Solution

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

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.

Follow us on Facebook and Twitter for latest update.