Python 中的 keys() 函数返回一个视图对象,该对象以列表形式显示字典中的所有键。
dict.keys()
keys() 不接受任何参数。当字典更新时,它将反映这些更改的键。
如果我们对字典进行任何更改,它也会反映到视图对象。如果字典为空,则返回一个空列表。
| 输入 | 返回值 |
|---|---|
| 字典 | 视图对象 |
persondet = {'name': 'Albert', 'age': 30, 'salary': 5000.0}
print(persondet.keys())
empty_dict
print(empty_dict.keys())
输出
dict_keys(['name', 'salary', 'age']) dict_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'])