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 dictionaryvalues()
: iterates over the values of the dictionaryitems()
: 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.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.