当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Dictionary keys()用法及代码示例


字典 keys() 方法

keys() 方法用于获取所有键作为视图对象,该视图对象包含字典的所有键。

用法:

    dictionary_name.keys()

参数:

  • 它不接受任何参数。

返回值:

这个方法的返回类型是<class 'dict_keys'>,它将字典的键作为视图对象返回。

范例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()))

输出

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'>

如果我们对字典进行任何更改,视图对象也将被反映,考虑给定的例子,

范例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)

输出

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'}

查看输出,值roll_no被改变。



相关用法


注:本文由纯净天空筛选整理自 Python Dictionary keys() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。