Explain with example Iterating over dictionaries using 'for' loops in Python

0
0

Iterating over dictionaries means looping through the keys, values, or key-value pairs (items) of a dictionary in order to access or manipulate its contents. In Python, dictionaries are unordered collections of key-value pairs, so when iterating over a dictionary, the order in which the keys, values, or items are returned is not guaranteed.

To iterate over a dictionary in Python, you can use a for loop with one of the following methods:

  • keys(): iterates over the keys of the dictionary
  • values(): iterates over the values of the dictionary
  • items(): iterates over the key-value pairs of the dictionary

In Python, you can use a for loop to iterate over the keys, values, or key-value pairs (items) in a dictionary. Here are some examples:

# Iterating over keys
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in my_dict:
print(key)

# Output:
# a
# b
# c

# Iterating over values
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for value in my_dict.values():
print(value)

# Output:
# 1
# 2
# 3

# Iterating over items (key-value pairs)
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key, value in my_dict.items():

In the first example, we use a for loop to iterate over the keys of the dictionary my_dict. Inside the loop, we print each key.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.