Python3 字典 setdefault() 方法

Python 3 教程 · 2019-02-06 16:42:21

描述

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

语法

setdefault()方法语法:

dict.setdefault(key, default=None)

参数

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

返回值

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

实例

以下实例展示了 setdefault() 方法的使用方法:

#!/usr/bin/python3

dict = {'Name': 'Codercto', 'Age': 7}

print ("Age 键的值为 : %s" %  dict.setdefault('Age', None))
print ("Sex 键的值为 : %s" %  dict.setdefault('Sex', None))
print ("新字典为:", dict)

以上实例输出结果为:

Age 键的值为 : 7
Sex 键的值为 : None
新字典为: {'Age': 7, 'Name': 'Codercto', 'Sex': None}

点击查看所有 Python 3 教程 文章: https://www.codercto.com/courses/l/10.html

查看所有标签

How to Design Programs

How to Design Programs

Matthias Felleisen、Robert Bruce Findler、Matthew Flatt、Shriram Krishnamurthi / The MIT Press / 2001-2-12 / 71.00美元

This introduction to programming places computer science in the core of a liberal arts education. Unlike other introductory books, it focuses on the program design process. This approach fosters a var......一起来看看 《How to Design Programs》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换