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 | Get total keys in dictionary
- Python | Minimum value keys in Dictionary
- Python | Add keys to nested dictionary
- Python | Count keys with particular value in dictionary
- Python | Get all tuple keys from dictionary
- Python Dictionary | keys() method
- Python | Get the number of keys with given value N in dictionary
- Python | Grouping dictionary keys by value
- Python | Remove multiple keys from dictionary
- Python | Remove spaces from dictionary keys
- Python | Remove Keys from dictionary starting with K
- Python | Initialize dictionary with multiple keys
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.

