1298

With Python 2.7, I can get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]

With Python >= 3.3, I get:

>>> newdict.keys()
dict_keys([1, 2, 3])

How do I get a plain list of keys with Python 3?

3
  • 38
    I'm new to Python, and to me it seems that this proliferation of useless new datatypes is one of the worst aspects of Python. Of what use is this dict_keys datatype? Why not a list?
    – Phil Goetz
    Apr 9, 2020 at 20:22
  • 17
    @PhilGoetz it saves memory by creating a view onto the dictionary that can use all the dictionary's data, rather than having to store a list of however many elements. It also provides some set operations (i.e., it can take advantage of the fact that it "knows" it does not contain duplicates), which are more efficient than checking e.g. the intersection of two lists. Aug 29, 2022 at 13:08
  • "With Python >= 3.3, I get:" - in fact, the change was introduced in 3.0. Mar 3 at 2:49

13 Answers 13

1609

This will convert the dict_keys object to a list:

list(newdict.keys())

On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For instance:

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

Note that dict_keys doesn't support insertion newdict[k] = v, though you may not need it.

13
  • 101
    newdict.keys() does not support indexing
    – gypaetus
    Sep 10, 2014 at 17:54
  • 98
    list(newdict) also works (at least in python 3.4). Is there any reason to use the .keys() method?
    – naught101
    Mar 31, 2015 at 11:58
  • 79
    Note: in the debugger pdb> list(newdict.keys()) fails because it clashes with pdb's command of the same name. Use pdb> !list(newdict.keys()) to escape pdb commands.
    – Rian Rizvi
    Dec 24, 2016 at 20:37
  • 43
    @naught101 Yes, .keys() is way more clear on what goes on.
    – Felix D.
    May 27, 2018 at 21:43
  • 13
    Note that if you use list(newdict.keys()) that the keys are not in the order you placed them due to hashing order!
    – Nate M
    Jan 30, 2019 at 3:28
529

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!

4
  • great explanation,but please can you refer any link which describes this "*newdict" type of syntax,I mean how and why this returns the keys from dictionary just for understanding.Thanx Apr 7, 2018 at 2:56
  • 3
    @MYounas That syntax has been available for quite some time, even in Python 2. In function calls you can do def foo(*args): print(args) followed by foo(*{1:0, 2:0}) with the result (1, 2) being printed. This behavior is specified in the Calls section of the reference manual. Python 3.5 with PEP 448 just loosened the restrictions on where these can appear allowing [*{1:0, 2:0}] to now be used. Either way, I'll edit my answer and include these. Apr 7, 2018 at 10:56
  • 7
    *newdict - this is definitely the answer for code golfers ;P. Also: which, in all honesty, isn't something you should really be worried about - and if you are, don't use python.
    – Miriam
    Apr 5, 2019 at 14:26
  • 7
    Learned two things today: 1. I can shorten list(some_dict.keys()) to [*some_dict], 2. the expression 'code golfer' (and 2a. the meaning of 'code golfer' - after Googling it)
    – kasimir
    Jul 8, 2020 at 12:16
74

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

0
38

You can also use a list comprehension:

>>> newdict = {1:0, 2:0, 3:0}
>>> [k  for  k in  newdict.keys()]
[1, 2, 3]

Or, shorter,

>>> [k  for  k in  newdict]
[1, 2, 3]

Note: Order is not guaranteed on versions under 3.7 (ordering is still only an implementation detail with CPython 3.6).

1
  • 18
    Just use list(newdict). There is no need for a list comprehension here.
    – Martijn Pieters
    Sep 27, 2019 at 12:15
31

A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]
1
  • 3
    You don’t even need to use .keys(); the dictionary object is itself iterable and produces keys when iterated over: [key.split(", ") for key in d].
    – Martijn Pieters
    Sep 27, 2019 at 12:16
27

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (Python3.x+):

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

Operation no. Of characters
k = list(d) 9 characters (excluding whitespace)
k = [*d] 6 characters
*k, = d 5 characters
4
  • 1
    The only minor caveat I'd point out is that k is always a list here. If a user wants a tuple or set from the keys they'll need to fall back to the other options. Apr 5, 2019 at 17:45
  • 1
    A more noteworthy note is the fact that, as a statement, *k, = d has limitations on where it can appear (but see, and maybe update this answer for, PEP 572 -- extended unpacking is not supported for assignment expressions atm but it might be someday!) Apr 5, 2019 at 17:55
  • what if you want both the keys and values to lists?
    – endolith
    Aug 26, 2019 at 23:26
  • 3
    @endolith perhaps keys, vals = zip(*d.items()) (although that gives two tuples, close enough). I don't know of a shorter expression than this. Aug 26, 2019 at 23:45
17

Converting to a list without using the keys method makes it more readable:

list(newdict)

and, when looping through dictionaries, there's no need for keys():

for key in newdict:
    print key

unless you are modifying it within the loop which would require a list of keys created beforehand:

for key in list(newdict):
    del newdict[key]

On Python 2 there is a marginal performance gain using keys().

14

Yes, There is a better and simplest way to do this in python3.X


use inbuild list() function

#Devil
newdict = {1:0, 2:0, 3:0}
key_list = list(newdict)
print(key_list) 
#[1, 2, 3] 
2
  • how is this different from @Seb's answer?
    – jochen
    Mar 3, 2022 at 11:29
  • @jochen : Code and simple explanation : )
    – Devil
    Mar 4, 2022 at 5:30
7

I can think of 2 ways in which we can extract the keys from the dictionary.

Method 1: - To get the keys using .keys() method and then convert it to list.

some_dict = {1: 'one', 2: 'two', 3: 'three'}
list_of_keys = list(some_dict.keys())
print(list_of_keys)
-->[1,2,3]

Method 2: - To create an empty list and then append keys to the list via a loop. You can get the values with this loop as well (use .keys() for just keys and .items() for both keys and values extraction)

list_of_keys = []
list_of_values = []
for key,val in some_dict.items():
    list_of_keys.append(key)
    list_of_values.append(val)

print(list_of_keys)
-->[1,2,3]

print(list_of_values)
-->['one','two','three']
6

Beyond the classic (and probably more correct) way to do this (some_dict.keys()) there is also a more "cool" and surely more interesting way to do this:

some_dict = { "foo": "bar", "cool": "python!" }
print( [*some_dict] == ["foo", "cool"] )         # True  

Note: this solution shouldn't be used in a develop environment; I showed it here just because I thought it was quite interesting from the *-operator-over-dictionary side of view. Also, I'm not sure whether this is a documented feature or not, and its behaviour may change in later versions :)

1
  • This works for Python3.7.
    – Good Fit
    Jan 23, 2023 at 18:32
1

You can you use simple method like below

keys = newdict.keys()
print(keys)
2
  • 1
    This answer is wrong. This returns a KeyView which is what the OP doesn't want. Oct 11, 2023 at 21:09
  • I'll just add that this is wrong, please edit or delete your answer. Dec 27, 2023 at 23:32
-1

This is the best way to get key List in one line of code

dict_variable = {1:"a",2:"b",3:"c"}  
[key_val for key_val in dict_variable.keys()]
1
  • I think you meant [key_val for key_val in dict_variable.keys()] Jun 26, 2021 at 8:12
-1
Get a list of keys with specific values

You can select a subset of the keys that satisfies a specific condition. For example, if you want to select the list of keys where the corresponding values are not None, then use

[k for k,v in newdict.items() if v is not None]
Slice the list of keys in a dictionary

Since Python 3.7, dicts preserve insertion order. So one use case of list(newdict) might be to select keys from a dictionary by its index or slice it (not how it's "supposed" to be used but certainly a possible question). Instead of converting to a list, use islice from the built-in itertools module, which is much more efficient since converting the keys into a list just to throw away most of it is very wasteful. For example, to select the second key in newdict:

from itertools import islice
next(islice(newdict, 1, 2))

or to slice the second to fifth key:

list(islice(newdict, 1, 6))

For large dicts, it's thousands of times faster than list(newdict)[1] etc.