如何取得 Python 3 中的字典鍵列表?

DDD
發布: 2024-11-14 18:30:02
原創
375 人瀏覽過

How do I get a list of dictionary keys in Python 3?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板