Exploring Methods to Iterate Through Dictionary Keys with 5 Examples
You can iterate over the keys in a dictionary using various methods in Python. Here are five examples:
- Using a for loop:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key)
- Using the
keys()
method:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict.keys():
print(key)
- Using a comprehension:
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = [key for key in my_dict]
print(keys)
- Using the
iterkeys()
method (Python 2):
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict.iterkeys():
print(key)
- Unpacking the dictionary directly:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(key)
All these methods achieve the same result of iterating over the keys of the dictionary.