如何在 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日

10.2万+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.