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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。