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
python— editable, runs on the server
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
python— editable, runs on the server
This will output:
a
b
cAnd here is an example using .values():
Iterate over the values of a Python dictionary
python— editable, runs on the server
This will output:
1
2
3