Python 字典 keys()

keys() 方法提取字典的键,并以视图对象的形式返回键的列表

示例

numbers = {1: 'one', 2: 'two', 3: 'three'}

# extracts the keys of the dictionary dictionaryKeys = numbers.keys()
print(dictionaryKeys) # Output: dict_keys([1, 2, 3])

keys() 语法

keys() 方法的语法是:

dict.keys()

其中,dict 是要提取键的字典。


keys() 参数

keys() 方法不接受任何参数。


keys() 返回值

keys() 方法返回

  • 一个视图对象,显示所有键的列表

例如,如果方法返回 dict_keys([1, 2, 3)]

  • dict_keys() 是视图对象
  • [1, 2, 3] 是键的列表

示例 1:Python 字典 keys()

employee = {'name': 'Phill', 'age': 22, 'salary': 3500.0}

# extracts the keys of the dictionary dictionaryKeys = employee.keys()
print(dictionaryKeys)

输出

dict_keys(['name', 'age', 'salary'])

在上面的示例中,我们使用了 keys() 方法来提取字典的键。键的列表以视图对象的形式返回。

这里,dict_keys() 是视图对象,['name', 'age', 'salary'] 是字典 employee 的键的列表。


示例 2:字典中的更新会更新视图对象

employee = {'name': 'Phill', 'age': 22}

# extracts the dictionary keys
dictionaryKeys = employee.keys()

print('Before dictionary update:', dictionaryKeys)

# adds an element to the dictionary employee.update({'salary': 3500.0})
# prints the updated view object print('After dictionary update:', dictionaryKeys)

输出

Before dictionary update
dict_keys(['name', 'age'])

After dictionary update
dict_keys(['name', 'age', 'salary'])

在上面的示例中,我们通过添加一个元素来更新字典,并使用 keys() 方法来提取键。

当字典元素更新时,dictionaryKeys 也会更新。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战