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']