How to create a list of dictionary keys in python

Published on Aug. 22, 2023, 12:16 p.m.

There are multiple ways to create a list of dictionary keys in Python. Here are a few examples:

  1. Using the “keys” method:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_list = list(my_dict.keys())
print(key_list)  # Output: ['a', 'b', 'c']
  1. Using the dictionary itself inside “list” method:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_list = list(my_dict)
print(key_list)  # Output: ['a', 'b', 'c']
  1. Using list comprehension:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key_list = [key for key in my_dict]
print(key_list)  # Output: ['a', 'b', 'c']

No matter which method you use all of them return a list of dictionary keys.

Tags: