In this shot, we explore different approaches through which we can return the dictionary keys as a list in Python.
dict.keys()
methodThe dict.keys()
method returns a view consisting of all the keys present in the dictionary. We can then use the list
constructor to convert this view into a list.
Let's see an example of this in the code snippet below:
# create a dictionarydata = {'name': 'Shubham','designation': 'Software Engineer'}# function to return the dictionary keys as a listdef convertDictKeysToList(d):return list(d.keys())# get dictionary keys as a listoutput = convertDictKeysToList(data)# print outputprint(output)
data
.convertDictKeysToList
function that returns the dictionary keys as a list using the dict.keys()
method.convertDictKeysToList
function and pass the data
dictionary as a parameter.Unpacking
operator:The Unpacking
operator unpacks the dictionary keys into a list using the following syntax:
[*dict]
This operator is supported in Python's versions 3.5 and above. Let's see an example of this operator in the code snippet below:
# create a dictionarydata = {'name': 'Shubham','designation': 'Software Engineer'}# function to return the dictionary keys as a listdef convertDictKeysToList(d):return [*d]# get dictionary keys as a listoutput = convertDictKeysToList(data)# print outputprint(output)
data
.convertDictKeysToList
function that returns the dictionary keys as a list using the Unpacking
operator.convertDictKeysToList
function and pass the data
dictionary as a parameter.