當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。