带有示例的Python字典get()方法

词典get()方法

get()方法用于根据指定的键获取元素的值。

语法:

    dictionary_name.fromkeys(keys, value)

Parameter(s):

  • key –它代表要返回其值的键的名称。

  • value –这是一个可选参数,用于指定如果项目不存在则返回的值。

返回值:

此方法的返回类型基于元素类型,它返回指定键上的元素,如果键不存在,则返回“ None”,如果我们定义了任何值,如果键不存在,则返回该值。

范例1:

# 带有示例的Python字典get()方法

# 字典声明
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# 印刷词典
print("data of student dictionary...")
print(student)

# 打印“ roll_no”的值"roll_no"
print("roll_no is:", student.get('roll_no'))

# 打印“ roll_no”的值"name"
print("name is:", student.get('name'))

# 打印“ roll_no”的值"course"
print("course is:", student.get('course'))

# 打印“ roll_no”的值"perc"
print("perc is:", student.get('perc'))

# 试图获取不存在的密钥项
print("address is:", student.get('address'))

# 试图获取不存在的密钥项
# 如果键不存在,则返回一些值
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字典get()方法

# 字典声明
x = {
    'key1' : 100,
    'key2' : 200,
    'key3' : 300
}

# 通过键定义值来获得价值
# 不存在
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.