π‘ Problem Formulation: Python dictionaries store data as key-value pairs. Sometimes, e.g., for the purpose of iteration or other operations, we may want to create a list out of just the keys from a dictionary.
Let’s explore some methods to do this, using a simple dictionary as an example:
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
sample_dict = {"apple": 1, "banana": 2, "cherry": 3}Our goal is to create a list: ["apple", "banana", "cherry"].
Method 1: Using list()
The list() constructor is the most straightforward approach to convert the dictionary keys into a list. By default, iterating a dictionary gives you its keys, so you can wrap it with list().
Code example:
keys_list = list(sample_dict) print(keys_list) # Output: ['apple', 'banana', 'cherry']
Here, list(sample_dict) converts the dictionary keys into a list.
π Dict to List β How to Convert a Dictionary to a List in Python
Method 2: Using dict.keys()
The dict.keys() method returns a view object that displays a list of all the keys. When you wrap it with list(), it converts that view into a list.
Code example:
keys_list = list(sample_dict.keys()) print(keys_list) # Output: ['apple', 'banana', 'cherry']
This will explicitly fetch the keys using sample_dict.keys() and then convert them to a list.
π How to Return Dictionary Keys as a List in Python?
Method 3: Using a for loop
If you need more control over the process, you can iterate through the dictionary with a for loop and append each key to a new list.
Code example:
keys_list = []
for key in sample_dict:
keys_list.append(key)
print(keys_list)
# Output: ['apple', 'banana', 'cherry']The for loop goes through each key in the dictionary and appends each to keys_list.
π Python Get List of Values from List of Keys
Method 4: Using List Comprehension
List comprehension is a concise way to achieve the same result as the for loop, but in a single, readable line.
Code example:
keys_list = [key for key in sample_dict] print(keys_list) # Output: ['apple', 'banana', 'cherry']
This line creates a new list, iterating through sample_dict and adding each key into the keys_list.
π Can a Python Dictionary Have a List as a Value?
Method 5: Using map()
The map() function can also be used to create a list of keys, although not as straight-to-the-point as the other methods.
Code example:
keys_list = list(map(lambda k: k, sample_dict)) print(keys_list) # Output: ['apple', 'banana', 'cherry']
This utilizes a lambda function that simply returns the key and maps it across the sample_dict, then converts the result to a list.
Bonus One-Liner Method 6: Using * Operator
With Python 3.5 and later, you can use the * operator, also known as the unpacking operator, within a list literal.
Code example:
keys_list = [*sample_dict] print(keys_list) # Output: ['apple', 'banana', 'cherry']
Here the * operator unpacks the keys from sample_dict directly into the list literal, creating keys_list.
Summary/Discussion
Creating a list from dictionary keys in Python can be done with several techniques ranging from simple, such as using list(), to more explicit ways, like iterating with a loop or comprehension.
Each method has its perks in different contexts, but they all effectively solve the problem. Whether you need a one-liner or a more customized solution, Python offers a rich set of tools for working with dictionaries and lists.
