Python – Get dictionary keys as a list



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

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']

Last Updated on October 15, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs