Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
dictionary

How to return the dictionary keys as a list in Python

Shubham Singh Kshatriya

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 dictionary
data = {
  'name': 'Shubham',
  'designation': 'Software Engineer'
}

# function to return the dictionary keys as a list
def convertDictKeysToList(d):
  return list(d.keys())

# get dictionary keys as a list
output = convertDictKeysToList(data)

# print output
print(output)
The implemenation of the dict.keys() method

Explanation

  • Lines 2-5: We create a dictionary named data.
  • Lines 8-9: We create a convertDictKeysToList function that returns the dictionary keys as a list using the dict.keys() method.
  • Line 12: We invoke the convertDictKeysToList function and pass the data dictionary 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 dictionary
data = {
  'name': 'Shubham',
  'designation': 'Software Engineer'
}

# function to return the dictionary keys as a list
def convertDictKeysToList(d):
  return [*d]

# get dictionary keys as a list
output = convertDictKeysToList(data)

# print output
print(output)
The implemenation of the Unpacking operator

Explanation

  • Lines 2-5: We create a dictionary named data.
  • Lines 8-9: We create the convertDictKeysToList function that returns the dictionary keys as a list using the Unpacking operator.
  • Line 12: We invoke the convertDictKeysToList function and pass the data dictionary as a parameter.
  • Line 15: We print the output to the console.

RELATED TAGS

python
communitycreator
dictionary

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring