Tutorial Study Image

Python keys()

Python 中的 keys() 函数返回一个视图对象,该对象以列表形式显示字典中的所有键。


dict.keys() 
 

keys() 参数

keys() 不接受任何参数。当字典更新时,它将反映这些更改的键。

keys() 返回值

如果我们对字典进行任何更改,它也会反映到视图对象。如果字典为空,则返回一个空列表。

输入 返回值
字典 视图对象

Python 中 keys() 方法的示例

示例 1:keys() 在 Python 中如何工作?


persondet = {'name': 'Albert', 'age': 30, 'salary': 5000.0}
print(persondet.keys())
 empty_dict
print(empty_dict.keys())
 

输出


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

示例 2:当字典更新时 keys() 的工作方式?


persondet = {'name': 'Albert', 'age': 30, }

print('Before dictionary is updated')
keys = persondet.keys()
print(keys)

# adding an element to the dictionary
persondet.update({'salary': 5000.0})
print('\nAfter dictionary is updated')
print(keys)
 

输出


Before dictionary is updated
dict_keys(['name', 'age'])

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