How to return dictionary keys as a list in Python?

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

提交回复
热议问题