In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this.
Using list()
The simplest and most efficient way to convert dictionary keys to lists is by using a built-in list() function.
d = {'a': 1, 'b': 2, 'c': 3}
a = list(d.keys())
print(a)
Output
['a', 'b', 'c']
Explanation:
- a.keys() returns a dict_keys object, which is a view object.
- Wrapping it with list() converts the view into a list.
Using List Comprehension
List Comprehension provide concise and readable way to create a list of keys.
d = {'a': 1, 'b': 2, 'c': 3}
a = [key for key in d]
print(a)
Output
['a', 'b', 'c']
Explanation:
- Iterating directly over the dictionary yields its keys.
- This method avoids calling
.keys()explicitly.
Using (* )Unpacking Operator
The unpacking operator (*) can be used to extract keys directly.
d = {'a': 1, 'b': 2, 'c': 3}
a = [*d]
print(a)
Output
['a', 'b', 'c']
Explanation:
- The unpacking operator expands the dictionary keys into a list.
Using map()
map() function can be used to explicitly iterate over the dictionary.
d = {'a': 1, 'b': 2, 'c': 3}
a = list(map(str,d))
print(a)
Output
['a', 'b', 'c']
Explantion:
- map() applies the identity function (or a custom function) to each key.
- Converting the result to a list yields the desired keys.