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

字典setdefault()方法 (Dictionary setdefault() Method)

setdefault() method is used to get the value of an item with the specified key and it sets an item (key, value) if the specified key does not exist in the dictionary.

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

Syntax:

句法:

    dictionary_name.setdefault(key, value)

Parameter(s):

参数:

  • key – It specifies the key name whose value to be returned to set.

    key –它指定要返回其值的键名。

  • value – It is an optional parameter, its default value is None, if the key does not exist, value becomes the value of the specified key.

    value –这是一个可选参数,其默认值为None ,如果键不存在,则value成为指定键的值。

Return value:

返回值:

The return type of this method is the type of the value, it returns the value of specified keys.

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

Note: If value is not defined, it returns None.

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

Example:

例:

# 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)

Output

输出量

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}


翻译自: https://www.includehelp.com/python/dictionary-setdefault-method-with-example.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值