Python 如何从字典中获取所有键的列表
在本文中,我们将展示如何使用不同的方法从Python字典中获取所有键的列表。我们可以使用以下方法从Python字典中获取所有键的列表:
- 使用dict.keys()方法
-
使用list()和dict.keys()函数
-
使用列表推导式
-
使用解包运算符(
*
) -
使用append()函数和for循环
假设我们有一个示例字典。我们将使用上述不同的方法返回Python字典中所有键的列表。
方法1:使用dict.keys()方法
在Python字典中,dict.keys()方法提供了一个显示字典中所有键的顺序列表的视图对象。
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储输入的字典,并向其中添加一些随机的键值对。
-
使用keys()函数将其应用于输入的字典,以获取字典的所有键的列表,并将其打印出来。
示例
以下程序使用keys()函数返回字典的所有键的列表:
# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# Printing the list of keys of a dictionary using keys() function
print(demoDictionary.keys())
输出
执行后,上述程序将生成以下输出:
dict_keys([10, 12, 14])
方法2:使用list()和dict.keys()函数
Python中的list()方法接受任何可迭代对象作为参数,并返回一个列表。可迭代对象是Python中可以迭代的对象。
步骤
以下是执行所需任务的算法/步骤 –
- 创建一个变量来存储输入的字典
-
使用keys()函数(dict.keys()方法提供了一个视图对象,该视图对象按照插入顺序显示字典中所有键的列表)打印字典所有键的列表,并使用list()函数将结果转换为列表(将序列/可迭代对象转换为列表)。
示例
以下程序使用list()和keys()函数返回字典所有键的列表 –
# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# Printing the list of keys of a dictionary using keys() function
# list() methods convert an iterable into a list
print(list(demoDictionary.keys()))
输出
[10, 12, 14]
方法3:使用列表解析
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储输入的字典。
-
使用keys()函数并将其应用于输入的字典,以获取字典的所有键的列表。
-
通过使用列表解析和 for 循环遍历上述键列表中的每个键,打印字典的键列表。
示例
以下程序使用列表解析返回字典的所有键的列表−
# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# getting all the keys from a dictionary
dictionaryKeys = demoDictionary.keys()
# Printing the list of keys of a dictionary by traversing through each key
# in the above keys list using the list comprehension
print([key for key in dictionaryKeys])
输出
[10, 12, 14]
方法4:使用解包运算符(*)
解包运算符 *
可以用于任何可迭代对象,并且由于字典在迭代时会返回其键,所以可以通过在列表字面量中使用解包运算符来轻松生成列表。
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储输入的字典。
-
使用解包运算符(
*
)和下面的语法来打印字典的所有键的列表(这里使用解包运算符 * 来解包字典的所有键,并使用*
作为解包运算符返回列表)。
print([*demoDictionary])
示例
以下程序使用解包运算符(*)返回字典的所有键列表-
# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# Printing the list of keys of a dictionary by using the unpacking operator(*)
print([*demoDictionary])
输出结果
[10, 12, 14]
方法5:使用append()函数和for循环
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储输入字典
-
创建一个空列表来存储输入字典的所有键
-
使用for循环遍历字典的所有键,并使用keys()函数遍历。
-
使用append()函数将字典的每个键添加到列表中(在列表末尾添加元素),并将相应的键作为参数传递给它。
-
打印字典的所有键的列表。
示例
以下程序使用append()函数和for循环返回字典的所有键的列表 –
# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# an empty list for storing dictionary keys
dictKeysList = []
# Traversing through all the keys of the dictionary
for dictKey in demoDictionary.keys():
# appending each key to the list
dictKeysList.append(dictKey)
# Printing the list of keys of a dictionary
print(dictKeysList)
输出
执行上述程序将会生成以下输出:
[10, 12, 14]
结论
本文教我们如何使用keys()函数来获取整个字典的键,并且如何使用list()函数将键转换为列表。此外,我们还学习了如何在同一段代码中使用列表生成式和for循环,将keys()方法返回的字典的键转换为列表。最后,我们还学习了如何使用append()函数向列表中添加元素(在这里我们添加了键)。