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']Method 1: Get dictionary keys as a list using dict.keys()
The dict.keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.
Python3
# Driver programdict = {1: 'Geeks', 2: 'for', 3: 'geeks'}print(dict.keys()) |
Output:
dict_keys([1, 2, 3])
Method 2: Get dictionary keys as a list using dict.keys()
Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over.
Python3
mydict = {1: 'Geeks', 2: 'for', 3: 'geeks'}keysList = list(mydict.keys())print(keysList) |
Output:
[1, 2, 3]
Method 3: Get dictionary keys as a list using For Loop and append method
In this method, we will iterate over each key using the dict.keys() function and append them to a new list named as a list.
Python3
# Python program to get# dictionary keys as listdef getList(dict): list = [] for key in dict.keys(): list.append(key) return list # Driver programdict = {1:'Geeks', 2:'for', 3:'geeks'}print(getList(dict)) |
Output:
[1, 2, 3]
Method 4: Dictionary Keys to List using List Comprehension
Here, we will try to shorten our code using list comprehension in Python.
Python3
dict = {1: 'Geeks', 2: 'for', 3: 'geeks'}keysList = [key for key in dict]print(keysList) |
Output:
[1, 2, 3]
Method 5: Dictionary Keys to List using 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.
Python3
def getList(dict): return [*dict]# Driver programdict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}print(getList(dict)) |
Output:
['a', 'b', 'c']
Method 6: Dictionary Keys to List using itemgetter
The itemgetter from the operator module returns a callable object that fetches an item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and then typecasted to list.
Python3
from operator import itemgetterdef getList(dict): return list(map(itemgetter(0), dict.items()))# Driver programdict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}print(getList(dict)) |
Output:
['a', 'b', 'c']





Please Login to comment...