Junior
How to get a list of keys from a dictionary in Python?
sobes.tech AI
Answer from AI
To get a list of keys from a dictionary in Python, you can use the .keys() method, convert the dictionary to a list directly, or use a list comprehension.
# Example dictionary
my_dict = {"a": 1, "b": 2, "c": 3}
# 1. Using .keys() method and converting to list
keys_list_1 = list(my_dict.keys())
# Gets an iterable `dict_keys` and converts it to a list
# 2. Directly converting dictionary to list
keys_list_2 = list(my_dict)
# Converting a dictionary to a list by default takes its keys
# 3. Using list comprehension
keys_list_3 = [key for key in my_dict]
# Iterates over dictionary keys and adds each to the list
# All methods will return the same list of keys
print(keys_list_1)
print(keys_list_2)
print(keys_list_3)