如何在 Python 中列印字典的所有鍵


Python **字典**是一種無序的資料值集合。與僅包含每個條目一個值的其他資料結構不同,Python 字典包含鍵:值對。本文介紹了在 Python 中列印字典所有鍵的各種方法。

使用 dict.keys() 方法

Python 的 dict.keys() 方法可用於檢索字典鍵,然後可以使用 print() 函式列印這些鍵。dict.keys() 方法的結果是一個檢視物件,顯示字典中每個鍵的列表。

可以使用 dict.keys() 方法訪問字典的元素,就像我們透過索引訪問列表一樣。

示例

以下是如何使用 dict.keys() 方法列印字典所有鍵的示例:

dictionary = { 'Novel': 'Pride and Prejudice', 'year': '1813', 'author': 'Jane Austen', 'character': 'Elizabeth Bennet' } print(dictionary.keys())

輸出

以下是上述程式碼的輸出:

['Novel', 'character', 'author', 'year']

使用 dictionary.items() 方法

內建的 Python 方法 items()用於檢索所有鍵和對應的值。我們可以透過將 items() 方法與 for 迴圈結合使用來列印字典的鍵和值。

如果您希望一次列印一個鍵,則此方法更實用。

示例

以下是如何使用 dictionary.items() 方法列印字典所有鍵的示例:

dictionary = { 'Novel': 'Pride and Prejudice', 'year': '1813', 'author': 'Jane Austen', 'character': 'Elizabeth Bennet' } for keys, value in dictionary.items(): print(keys)

輸出

以下是上述程式碼的輸出 

Novel
character
author
year

透過建立所有鍵的列表

我們還可以從 dict.keys() 函式給出的可迭代序列中生成一個鍵列表。然後列印列表的全部內容(字典的所有鍵)。

示例

以下是如何透過建立所有鍵的列表來列印字典所有鍵的示例:

dictionary = { 'Novel': 'Pride and Prejudice', 'year': '1813', 'author': 'Jane Austen', 'character': 'Elizabeth Bennet' } # Getting all the keys of a dictionary as a list list_of_the_keys = list(dictionary.keys()) # Printing the list which contains all the keys of a dictionary print(list_of_the_keys)

輸出

以下是上述程式碼的輸出。

['Novel', 'character', 'author', 'year']

透過建立列表推導式

我們還可以使用此列表推導式透過迭代所有鍵來重複列印字典中的每個鍵。

示例

以下是如何透過建立列表推導式來列印字典所有鍵的示例:

dictionary = { 'Novel': 'Pride and Prejudice', 'year': '1813', 'author': 'Jane Austen', 'character': 'Elizabeth Bennet' } # Iterating over all the keys of a dictionary and printing them one by one [print(keys) for keys in dictionary]

輸出

以下是上述程式碼的輸出:

Novel
year
author
character

使用 itemgetter 模組

來自 operator 模組的 itemgetter 返回一個可呼叫物件,該物件使用運算元的 __getitem__() 方法從中檢索專案。然後在對映到 dict.items() 後將該方法型別轉換為列表。

示例

以下是如何使用 itemgetter 列印字典所有鍵的示例:

from operator import itemgetter def List(dictionary): return list(map(itemgetter(0), dictionary.items())) dictionary = { 'Novel': 'Pride and Prejudice','year': '1813','author': 'Jane Austen','character': 'Elizabeth Bennet'} print(List(dictionary))

輸出

以下是上述程式碼的輸出。

['Novel', 'character', 'author', 'year']

更新於: 2023年8月23日

102K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告