How to return dictionary keys as a list in Python?

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

提交回复
热议问题