w3resource

Python: Iterate over dictionaries using for loops

Python dictionary: Exercise-5 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-5.php