Obtain list of keys of a Dictionary in Python
To obtain list of keys of a Dictionary in Python, the dictionary offers keys()
method. It returns a collection of type dict_keys
.
d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
keys = d1.keys()
print(keys)
print(f'Type of keys is: {type(keys)}')
dict_keys(['Bob', 'Alice', 'Ram', 'Geeta', 'Shreyan', 'Raj'])
Type of keys is: <class 'dict_keys'>
If we want to get all the keys of a dictionary as a type of list
, we can do so using list comprehension as follows.
d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
keys =[key for key in d1.keys()]
print(keys)
print(f'Type of keys is: {type(keys)}')
The output of the preceding code will return a collection of keys
of type list
as shown as follows.
['Bob', 'Alice', 'Ram', 'Geeta', 'Shreyan', 'Raj']
Type of keys is: <class 'list'>