📅  最后修改于: 2020-09-20 04:47:17             🧑  作者: Mango
setdefault()
的语法为:
dict.setdefault(key[, default_value])
setdefault()
最多接受两个参数:
default_value
值的key
插入到字典中。如果未提供,则default_value
将为None
。 setdefault()
返回:
key
值(如果它在字典中) default_value
如果key
不在字典和default_value
指定person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age)
输出
person = {'name': 'Phill', 'age': 22}
Age = 22
person = {'name': 'Phill'}
# key is not in the dictionary
salary = person.setdefault('salary')
print('person = ',person)
print('salary = ',salary)
# key is not in the dictionary
# default_value is provided
age = person.setdefault('age', 22)
print('person = ',person)
print('age = ',age)
输出
person = {'name': 'Phill', 'salary': None}
salary = None
person = {'name': 'Phill', 'age': 22, 'salary': None}
age = 22