如何在 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']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

