How to return the dictionary keys as a list in Python
Overview
In this shot, we explore different approaches through which we can return the dictionary keys as a list in Python.
Approach 1: The dict.keys() method
The 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)
Explanation
- Lines 2-5: We create a dictionary named
data. - Lines 8-9: We create a
convertDictKeysToListfunction that returns the dictionary keys as a list using thedict.keys()method. - Line 12: We invoke the
convertDictKeysToListfunction and pass thedatadictionary as a parameter. - Line 15: We print the output to the console.
Approach 2: The 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)
Explanation
- Lines 2-5: We create a dictionary named
data. - Lines 8-9: We create the
convertDictKeysToListfunction that returns the dictionary keys as a list using theUnpackingoperator. - Line 12: We invoke the
convertDictKeysToListfunction and pass thedatadictionary as a parameter. - Line 15: We print the output to the console.