如何在 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']
廣告