How to return dictionary keys as a list in Python?

后端 未结 8 1890
长情又很酷
长情又很酷 2020-11-22 07:42

In Python 2.7, I could get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>&g         


        
相关标签:
8条回答
  • 2020-11-22 08:14

    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!

    0 讨论(0)
  • 2020-11-22 08:14

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

    0 讨论(0)
  • 2020-11-22 08:14

    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']
    
    0 讨论(0)
  • 2020-11-22 08:15

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

    0 讨论(0)
  • 2020-11-22 08:23

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

    0 讨论(0)
  • 2020-11-22 08:27

    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.

    0 讨论(0)
提交回复
热议问题