Python Get Dictionary Keys as a List

How to get Python Dictionary Keys as a List? To get all dictionary keys as a list in Python use the keys() method and covert the returned object to a list using list(). We can also get keys from a dictionary using various ways in Python. In dictionaries, elements are presented in the form of key:value pairs and all keys are associated with their corresponding values.

Methods to get Dictionary Keys as a List:

  1. list(dict.keys()) returns the dictionary keys as a list.
  2. You can use for loop to iterate the dictionary and get the key from each iteration.
  3. Use a list comprehension to get all keys from the dictionary.
  4. Finally use map() with lambda to get all keys.

1. Quick Examples of Dictionary Keys as a List

If you are in a hurry, below are some quick examples of getting dictionary keys as a list in Python.


# Quick examples of dictionary keys as a list

# Example 1: Get the keys of dictionary as a list 
# using .keys() & list()
keys = list(my_dict.keys())

# Example 2: Get the keys 
# Using for loop
mylist = []
for key in my_dict.keys():
    mylist.append(key)

# Example 3: Get the keys as a list 
# Using dictionary comprehension
keys = [key for key in my_dict]

# Example 4: Use map and lambda 
# Get the keys of dict
mykeys = list(map(lambda x: x[0], my_dict.items()))

# Example 5: Using * operator 
# Get the keys
print([*my_dict])

2. What is Python Dictionary

A Python dictionary is a key-value collection that is unordered, mutable, and does not allow duplicate keys. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key:value pair separated by commas. The dictionaries are indexed by keys.

Dictionaries are mutable hence, you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value. Let’s create a Python dictionary,


# Create dictionary
my_dict = {'course':'python','fee':4000,'duration':'60days','discount':1200}
print("Create dictionary:\n",my_dict)

Yields below output.

Python- dictionary- keys-list

3. Python Get Dictionary keys as a List

To get dictionary keys as a list in Python use the dict.keys() which returns the keys in the form of dict_keys() and use this as an argument to the list(). The list() function takes the dict_keys as an argument and converts it to a list, this will return all keys of the dictionary in the form of a list. Here, is an example.


# Get the keys of dictionary as a list 

# my_dict.keys()
print("Get the keys of the dictionary as a list:")
print(my_dict.keys())

# type
print("Type:")
print(type(my_dict.keys()))

# Convert to list
keys = list(my_dict.keys())
print("Convert to list:\n",keys)

Yields below output.

Python- dictionary- keys-list

4. Get Keys as a List using Looping

Use for loop to iterate a Python dictionary over keys, by default when you use for loop with dict, it returns a key from the dict for each iteration, add the key to the list to get all keys as a list.

In the below example, the dictionary my_dict has keys ‘course’, ‘fee’, ‘duration’, and ‘discount’. The for loop iterates over the keys, and each key is appended to the list mylist.


# Get the keys using for loop
mylist = []

for key in my_dict.keys():
    mylist.append(key)

print(mylist)

# Output:
# ['course', 'fee', 'duration', 'discount']

5. Get Keys using List Comprehension

Alternatively, using list comprehension we can get all the keys of the Python dictionary. Let’s use list comprehension(a concise way of creating a new list) and get the list of all keys.

You can use list comprehension to obtain the keys of a dictionary as a list in a more concise manner. For instance, the list comprehension [key for key in my_dict] creates a new list containing all the keys of the dictionary.


# Get the keys as a list using dictionary comprehension
keys = [key for key in my_dict]
print(keys)

# Output
# ['course', 'fee', 'duration', 'discount']

6. Get Keys as a List using Map and lambda

We can also get the keys as a list using another approach i.e. the combination of a map() function and a lambda function. Let’s use both functions and get our desired output.

In the below example, my_dict.items() returns a view of key-value pairs as tuples, and lambda x: x[0] is used to extract the keys from each tuple. The map function applies this lambda function to each tuple in the view, and list() converts the result to a list. The final result, myList, contains the keys of the dictionary as a list.


# Use map and lambda to get the keys of dict
myList = list(map(lambda x: x[0], my_dict.items()))
print(myList)

# Output:
# ['course', 'fee', 'duration', 'discount']

Here, lambda expression is called for each item in the dictionary and x[0] gives you a key from each item.

7. Using Unpacking operator(*) & Get the Keys

Using the unpacking operator '*' we can get the all keys from the Python dictionary. This operator works with any iterable object and returns a list. Let’s apply '*' operator on the given dictionary.


# Using * operator get the keys
print([*my_dict])

# Output:
# ['course', 'fee', 'duration', 'discount']

Frequently Asked Questions on Python Get Dictionary Keys as a List

How can I get the keys of a dictionary as a list in Python?

To get the keys of a dictionary as a list, you can use the keys() method of the dictionary and convert it to a list using the list() constructor.

Can I achieve the same result without using the list() function?

You can achieve the same result without using the list() function by using a list comprehension directly with the dictionary.

Is there a difference between using list(my_dict.keys()) and list(my_dict)?

Both approaches will give you the same result. Using list(my_dict.keys()) explicitly calls the keys() method, while list(my_dict) implicitly uses the default iteration over the dictionary keys.

Are there any performance considerations when converting keys to a list?

Converting keys to a list is generally efficient. However, keep in mind that it creates a new list object, so it consumes additional memory. If memory is a concern, consider using other iterable forms like dict_keys directly without converting to a list.

Can I use map() and lambda to get dictionary keys as a list?

You can use map() and lambda to get dictionary keys as a list. For example, my_dict.items() returns a view of key-value pairs as tuples, and lambda x: x[0] is used to extract the keys from each tuple. The map() function applies this lambda function to each tuple in the view, and list() converts the result to a list.

Which method is more Pythonic?

Using the keys() method or a list comprehension is generally considered more Pythonic. The list comprehension is concise and easy to read, making it a popular choice.

Conclusion

In this article, I have explained how to get a Python dictionary keys as a list. You can achieve this in several ways, for example, using list(dict.keys), using map() with lambda, and list comprehension.

References

Naveen

Naveen (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn LinkedIn

Leave a Reply