Convert Dictionary Keys to a List in Python

Converting dictionary keys to a list allows you to extract the keys and store them as separate elements. In this blog post, we will explore different methods to convert dictionary keys to a list in Python.

Method 1: Using the keys() Method

# Method 1: Using the keys() Method
my_dict = {"name": "John", "age": 30, "city": "New York"}
key_list = list(my_dict.keys())
print("Keys as list:", key_list)

Output:

Keys as list: [‘name’, ‘age’, ‘city’]

Method 2: Using Dictionary Comprehension

# Method 2: Using Dictionary Comprehension
my_dict = {"name": "John", "age": 30, "city": "New York"}
key_list = [key for key in my_dict]
print("Keys as list:", key_list)

Output:

Keys as list: [‘name’, ‘age’, ‘city’]