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]

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:



[1, 2, 3]

 
Approach #2 : Naive approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[1, 2, 3]

 
Approach #3 : Typecasting to list

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

['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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

['b', 'a', 'c']


My Personal Notes arrow_drop_up


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.