How to iterate through a dictionary in python
- User
How to iterate through a dictionary in python
- Assistant
Iterating through a dictionary in Python can be done in several ways, depending on what you need to accomplish. Below are some common methods:
1. Iterating through Keys
You can iterate through the keys of a dictionary using a
forloop.my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict: print(key)2. Iterating through Values
You can iterate through the values in the dictionary using the
values()method.my_dict = {'a': 1, 'b': 2, 'c': 3} for value in my_dict.values(): print(value)3. Iterating through Key-Value Pairs
You can iterate through the key-value pairs using the
items()method.my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(f"Key: {key}, Value: {value}")