How to return dictionary keys as a list in Python? How to return dictionary keys as a list in Python? python python

How to return dictionary keys as a list in Python?


Try list(newdict.keys()).

This will convert the dict_keys object to a list.

On the other hand, you should ask yourself whether or not it matters. The Pythonic way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it's a duck). The dict_keys object will act like a list for most purposes. For instance:

for key in newdict.keys():  print(key)

Obviously, insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway.


Python >= 3.5 alternative: unpack into a list literal [*newdict]

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

>>> newdict = {1:0, 2:0, 3:0}>>> [*newdict][1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]1000000 loops, best of 3: 249 ns per loop%timeit list(newdict)1000000 loops, best of 3: 508 ns per loop%timeit [k for k in newdict]1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,(1, 2, 3)>>> {*newdict}{1, 2, 3}

beware of the trailing comma in the tuple case!


list(newdict) works in both Python 2 and Python 3, providing a simple list of the keys in newdict. keys() isn't necessary. (: