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


Python Dictionary get()用法及代碼示例

字典 get() 方法

get() 方法用於根據指定的鍵獲取元素的值。

用法:

    dictionary_name.fromkeys(keys, value)

參數:

  • key– 它表示要返回其值的鍵的名稱。
  • value– 可選參數,用於指定item不存在時返回的值。

返回值:

此方法的返回類型基於元素類型,它返回指定鍵上的元素,如果鍵不存在則返回 "None",如果我們定義了任何值,如果鍵不存在則返回該值。

範例1:

# Python Dictionary get() 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 the value of "roll_no"
print("roll_no is:", student.get('roll_no'))

# printing the value of "name"
print("name is:", student.get('name'))

# printing the value of "course"
print("course is:", student.get('course'))

# printing the value of "perc"
print("perc is:", student.get('perc'))

# trying to get item of the key which does not exist
print("address is:", student.get('address'))

# trying to get item of the key which does not exist
# and returning some value if key does not exist
print("address is:", student.get('address', "does not exist."))

輸出

data of student dictionary...
{'perc':98.5, 'course':'B.Tech', 'name':'Shivang', 'roll_no':101}
roll_no is:101
name is:Shivang
course is:B.Tech
perc is:98.5
address is:None
address is:does not exist.

範例2:

# Python Dictionary get() Method with Example

# dictionary declaration
x = {
    'key1':100,
    'key2':200,
    'key3':300
}

# getting value with defining value if key
# does not exist
print("key1 = ", x.get('key1', "Item does not exist."))
print("key2 = ", x.get('key2', "Item does not exist."))
print("key3 = ", x.get('key3', "Item does not exist."))
print("key4 = ", x.get('key4', "Item does not exist."))

輸出

key1 =  100
key2 =  200
key3 =  300
key4 =  Item does not exist.


相關用法


注:本文由純淨天空篩選整理自 Python Dictionary get() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。