Python 字典(Dictionary) setdefault()方法

栏目: 编程语言 · Python · 编程教程 · python 教程 · 发布时间: 7年前

内容简介:Python 字典 setdefault() 函数和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。

描述

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

语法

setdefault()方法语法:

dict.setdefault(key, default=None)

参数

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

返回值

如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。

实例

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
dict = {'codercto': 'coder码农', 'google': 'Google 搜索'}
 
print "Value : %s" %  dict.setdefault('codercto', None)
print "Value : %s" %  dict.setdefault('Taobao', '淘宝')

以上实例输出结果为:

Value : coder码农
Value : 淘宝

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Neural Networks for Applied Sciences and Engineering

Neural Networks for Applied Sciences and Engineering

Samarasinghe, Sandhya / CRC Pr I Llc / 2006-9 / $ 118.59

In response to the exponentially increasing need to analyze vast amounts of data, Neural Networks for Applied Sciences and Engineering: From Fundamentals to Complex Pattern Recognition provides scient......一起来看看 《Neural Networks for Applied Sciences and Engineering》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具