Python converting a dictionary's keys to a list
We can use list() function to convert a dictionary's keys to a list. The dictionary's keys can be obtained via the keys() method.
Example
my_dict
=
{
'name'
:
'Alice'
,
'age'
:
25
,
'city'
:
'New York'
}
keys_list
=
list
(
my_dict.
keys
(
)
)
(
keys_list
)
Code analysis:
my_dictis a dictionary containing three key-value pairs.my_dict.keys()Returns all keys of the dictionary; the return type is a view object.list(my_dict.keys())Converts the view object to a list.print(keys_list)Outputs the converted list.
Output result:
['name', 'age', 'city']
Python3 Examples