Retrieving Dictionary Keys as List in Python
In Python 2.7, obtaining a list of dictionary keys is straightforward:
newdict = {1:0, 2:0, 3:0} newdict.keys()
However, in Python 3.3 onwards, the output is a "dict_keys" object, not a list:
newdict.keys()
This article explores how to obtain a plain list of keys in Python 3.
Converting dict_keys to List
To convert the dict_keys object to a list, use list comprehension:
list(newdict.keys())
This will produce a list of keys:
[1, 2, 3]
Duck Typing Consideration
However, it's important to consider if converting to a list is necessary. Pythonic principles encourage "duck typing," where objects can be treated as their intended type if they exhibit the correct behavior. In this case, dict_keys can be iterated over like a list:
for key in newdict.keys(): print(key)
This code will iterate through the keys and print them one by one.
Insertion Considerations
Note that dict_keys does not support insertions, so the following code will not work:
newdict.keys()[0] = 10 # Will result in TypeError
If you require insertion functionality, you should use a list instead of dict_keys.
以上是如何取得 Python 3 中的字典鍵列表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!