Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Get dictionary keys as a list

  • Difficulty Level : Hard
  • Last Updated : 28 Jan, 2019

Given a dictionary, write a Python program to get the dictionary keys as a list.

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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))
Output:
[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))
Output:
[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))
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.




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




# 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))
Output:
['b', 'a', 'c']



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!