How to Return Dictionary Keys as a List in Python

Created
Modified

Using keys Function

The dict.keys() function returns a view object that displays a list of all the keys in the dictionary in order of insertion.

See the following example:

#!/usr/bin/python3

d = {"a": 1, "c": 2, "b": 3}
keys = list(d.keys())
print(keys)
['a', 'c', 'b']

Using Unpacking

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

#!/usr/bin/python3

d = {"a": 1, "c": 2, "b": 3}
# Python >= 3.5
keys = [*d]
print(keys)
['a', 'c', 'b']

Using Extended Iterable Unpacking

The following example should cover whatever you are trying to do:

#!/usr/bin/python3

d = {"a": 1, "c": 2, "b": 3}
# Python >= 3.x
*keys, = d
print(keys)
['a', 'c', 'b']

Related Tags

#return# #key# #list#