python 示例
(Dictionary keys() Method)
keys() method
keys()方法用于获取所有键作为视图对象,该视图对象包含字典的所有键。
Syntax:
句法:
dictionary_name.keys()
Parameter(s):
参数:
- It does not accept any parameter.
它不接受任何参数。
Return value:
返回值:
The return type of this method is <class 'dict_keys'>, it returns the keys of the dictionary as view object.
此方法的返回类型为<class'dict_keys'> ,它将字典的键作为视图对象返回。
Example 1:
范例1:
# Python Dictionary keys() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# printing keys
print("keys of student dictionary...")
print(student.keys())
# printing return type of student.keys() Method
print("return type is: ", type(student.keys()))
Output
输出量
data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
return type is: <class 'dict_keys'>
If we make any changes in the dictionary, view object will also be reflected, consider the given example,
如果我们在字典中进行任何更改,则视图对象也将得到反映,请考虑给定的示例,
Example 2:
范例2:
# Python Dictionary keys() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# printing keys
print("keys of student dictionary...")
print(student.keys())
# changing a value
student['roll_no'] = 999
# printing dictionary
print("data of student dictionary after update...")
print(student)
Output
输出量
data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
data of student dictionary after update...
{'course': 'B.Tech', 'roll_no': 999, 'perc': 98.5, 'name': 'Shivang'}
See the output, value of roll_no
看到输出, roll_no的值已更改。