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)}')
Get all keys of a Dictionary in Python
dict_keys(['Bob', 'Alice', 'Ram', 'Geeta', 'Shreyan', 'Raj'])
Type of keys is: <class 'dict_keys'>
Output: Get all keys of a Dictionary in Python

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)}')
Get list of all keys of a Dictionary in Python

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'>
Output: Get list of all keys of a Dictionary in Python