Python Program to Iterate Over Dictionaries Using for Loop


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In Python, a dictionary is a collection of key-value pairs. Each key-value pair in a dictionary is called an item. Dictionaries are also sometimes called associative arrays, maps or hash tables in other programming languages.


Python Code :

The below Python program iterates over a dictionary using a for loop:


# Define a dictionary of student names and their scores
scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Dave': 95}

# Loop through the dictionary using items()
for name, score in scores.items():
    print(f"{name}'s score is {score}.")

Output:


Alice's score is 85.
Bob's score is 92.
Charlie's score is 78.
Dave's score is 95.

In this program, we first define a dictionary called scores that contains student names as keys and their scores as values.

We then loop through the dictionary using the items() method, which returns a list of tuples that contain each key-value pair in the dictionary. We use two variables, name and score, to represent the key and value of each item in the dictionary.

Inside the loop, we print a message that displays the name and score of each student. The f-string is used to format the message with the values of name and score.

Note that the order in which the items are returned by items() is not guaranteed to be the same order in which they were inserted into the dictionary. If you need to iterate over the items in a specific order, you should use an ordered dictionary instead.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co