Python语言基础
Python语言进阶
Python数据结构

Python dictionary setdefault() 方法

搞懂Python dictionary setdefault() 方法的用法

描述

Python 字典 setdefault() 方法和 get()方法 类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。

语法

setdefault()方法语法:
dict.setdefault(key, default=None)

参数

key -- 查找的键值。 default -- 键不存在时,设置的默认键值。

返回值

如果 key 在 字典中,返回对应的值。如果不在字典中,则插入 key 及设置的默认值 default,并返回 default ,default 默认值为 None。

实例

以下实例展示了 setdefault() 方法的使用方法:
dict = { 'Name' : 'lidihuo' , 'Url' : 'www.lidihuo.com' }
print( "Age 键的值为 : %s " % dict.setdefault('Url' , None))
print( "Course 键的值为 : %s " % dict.setdefault('Course' , None))
print( "新字典为:" , dict)
以上实例输出结果为:
Age 键的值为 : www.lidihuo.com
Course 键的值为 : None
新字典为: {'Name': 'lidihuo', 'Url': 'www.lidihuo.com', 'Course': None}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4