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


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


字典 setdefault() 方法

setdefault() 方法用于获取具有指定键的项目的值,如果指定的键在字典中不存在,则设置项目(键,值)。

用法:

    dictionary_name.setdefault(key, value)

参数:

  • key– 指定要返回设置其值的键名。
  • value– 可选参数,默认值为None,如果 key 不存在,value成为指定键的值。

返回值:

该方法的返回类型是值的类型,它返回指定键的值。

注意:如果value未定义,它返回None

例:

# Python Dictionary setdefault() 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)

# getting value of 'roll_no'
x = student.setdefault('roll_no', 0)
print('roll_no:', x)

# getting value of address key
# that does not exist, then function
# inserts given key & value
x = student.setdefault('address', 'New Delhi')
print('address:', x)

# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)

# getting value of age key
# that does not exist, then function
# inserts given key & None
x = student.setdefault('age')
print('age:', x)

# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)

输出

data of student dictionary...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5}
roll_no: 101
address: New Delhi
data of student dictionary after setdefault()...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'address':'New Delhi'}
age: None
data of student dictionary after setdefault()...
{'roll_no':101, 'name':'Shivang', 'course':'B.Tech', 'perc':98.5, 'address':'New Delhi', 'age':None}


相关用法


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