Python convert a dictionary's keys to a list

Document 对象参考手册Python3 Examples

We can use thelist()function to convert the dictionary's keys to a list. The dictionary's keys can be obtained using thekeys()method.

Example

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
keys_list = list(my_dict.keys())
print(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)prints the converted list.

Output:

['name', 'age', 'city']

Document 对象参考手册Python3 Examples

Other extensions