Python Dictionary Keys: How to Get Values
You can use the keys() method to access all the keys in a dictionary. This method returns a view object containing all the keys in the dictionary, which can be converted into a list or iterator to access the key values.
Here are several common ways to access dictionary keys:
- list of keys
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = list(my_dict.keys())
print(keys) # 输出 ['a', 'b', 'c']
- Iterate directly through the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key) # 输出 a, b, c
- retrieve a list of all keys
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys_iter = my_dict.keys()
for key in keys_iter:
print(key) # 输出 a, b, c
Note: In Python 3, the keys() method returns a view object, rather than a list. This is beneficial as it can save memory, especially when the dictionary is very large.