Signup/Sign In

How to get Dictionary keys as a List in Python?

Posted in Programming   LAST UPDATED: SEPTEMBER 1, 2021

    In Python 2.x version, this was easy because the function dict.keys() by default returned a list of keys of the dictionary but that is not the case with Python 3.x version.

    In Python 3.x if we use this code, the dict.keys() function returns a dictionary view object which acts as a set.

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


    dict_keys([1, 2, 3])

    So this won't work in Python 3.x version but there are many other ways to get dictionary keys in a list.

    Directly convert Dictionary to List

    By default, iterating over a python dictionary returns the dictionary keys, hence if we use the list() method with the dictionary object we will get a list of dictionary keys. For example,

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


    [1, 2, 3]

    Convert the Dictionary Keys to List

    We can use the dict.keys() method to get the dictionary view object for list, but then we can use the list() function to directly convert it into a list.

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


    [1, 2, 3]

    Using the Unpacking Operator

    The unpacking operator 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.

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


    [1, 2, 3]

    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).

    Using List Comprehension

    Well although the different ways listed above would be enough, but let's give you one more option which is using list comprehension technique in which we will be using the dict.keys() function too.

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


    [1, 2, 3]


    So now you know 4 ways of getting dictionary keys in form of list. Python has this advantage that one task can be accomplished by many simple techniques. If you know any other technique then do share it with us in comments.

    You may also like:

    About the author:
    This is the official profile of the Studytonight content team.
    Tags:PythonPython DictionaryProgramming

    Want to learn coding and don't know where to start?

    Try out our Interactive Courses for Free 🥳 😯 🤩
    learn to code footer Ad