Iterating over dictionaries using 'for' loops
To iterate over a dictionary using a for loop, you can use the .items() method to get a list of the dictionary's keys and values, and then iterate over that list.
To iterate over a dictionary using a for loop, you can use the .items() method to get a list of the dictionary's keys and values, and then iterate over that list. Here is an example:
Iterate over a dictionary using a for loop in Python
d = {'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
print(key, value)This will output:
a 1
b 2
c 3You can also use the .keys() method to iterate just over the keys or the .values() method to iterate just over the values. Here is an example using .keys():
Iterate over the keys of a Python dictionary
for key in d.keys():
print(key)This will output:
a
b
cAnd here is an example using .values():
Iterate over the values of a Python dictionary
for value in d.values():
print(value)This will output:
1
2
3