Python | Get dictionary keys as a list
Given a dictionary, write a Python program to get the dictionary keys as a list.
Examples:
Input : {1:'a', 2:'b', 3:'c'}
Output : [1, 2, 3]
Input : {'A' : 'ant', 'B' : 'ball'}
Output : ['A', 'B']
Approach #1 : Using dict.keys() [For Python 2.x]
# Python program to get # dictionary keys as list def getList(dict): return dict.keys() # Driver program dict = {1:'Geeks', 2:'for', 3:'geeks'} print(getList(dict)) |
[1, 2, 3]
Approach #2 : Naive approach.
# Python program to get # dictionary keys as list def getList(dict): list = [] for key in dict.keys(): list.append(key) return list # Driver program dict = {1:'Geeks', 2:'for', 3:'geeks'} print(getList(dict)) |
[1, 2, 3]
Approach #3 : Typecasting to list
# Python program to get # dictionary keys as list def getList(dict): return list(dict.keys()) # Driver program dict = {1:'Geeks', 2:'for', 3:'geeks'} print(getList(dict)) |
[1, 2, 3]
Approach #4 : Unpacking with *
Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.
# Python program to get # dictionary keys as list def getList(dict): return [*dict] # Driver program dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'} print(getList(dict)) |
['c', 'a', 'b']
Approach #5 : Using itemgetter
itemgetter from operator module return a callable object that fetches item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and them typecasted to list.
# Python program to get # dictionary keys as list from operator import itemgetter def getList(dict): return list(map(itemgetter(0), dict.items())) # Driver program dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'} print(getList(dict)) |
['b', 'a', 'c']
Recommended Posts:
- Python | Initialize a dictionary with only keys from a list
- Python | Sort dictionary keys to list
- Python | Add new keys to a dictionary
- Python | Add keys to nested dictionary
- Python Dictionary | keys() method
- Python | Minimum value keys in Dictionary
- Python | Ways to change keys in dictionary
- Python | Remove spaces from dictionary keys
- Python | Extract specific keys from dictionary
- Python dictionary with keys having multiple inputs
- Python | Remove multiple keys from dictionary
- Python | Remove Keys from dictionary starting with K
- Python | Find keys with duplicate values in dictionary
- Python | Test if dictionary contains unique keys and values
- Python program to Swap Keys and Values in Dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



