How to return dictionary keys as a list in Python?

后端 未结 8 1896
长情又很酷
长情又很酷 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: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).

提交回复
热议问题