python字典get()方法用法分析

yipeiwu_com6年前Python基础

本文实例讲述了python字典get()方法用法。分享给大家供大家参考。具体分析如下:

如果我们需要获取字典值的话,我们有两种方法,一个是通过dict['key'],另外一个就是dict.get()方法。

这里给大家分享的就是字典的get()方法。

这里我们可以用字典做一个小游戏,假设用户在终端输入字符串:"1"或者是"2"或者是"3",返回对应的内容,如果是输入其他的,则返回"error"

>>> info = {'1':'first','2':'second','3':'third'}
>>> number = raw_input('input type you number:')
input type you number:3
>>> print info.get(number,'error')
third
>>> number = raw_input('input type you number:')
input type you number:4
>>> print info.get(number,'error')
error

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Pycharm设置界面全黑的方法

win7 pycharm设置界面全黑色方法: 1.设置默认PyCharm解析器: 操作如下: Python–>Preferences–>Project Interprete...

详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本

详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本

0.配置依赖环境,如果不进行这步可能会出现一些问题 中间可能有多余空格,去除下再运行,一般都能安装成功,如果不能可以先更新下sudo apt-get update sudo apt-...

tensorflow 1.0用CNN进行图像分类

tensorflow升级到1.0之后,增加了一些高级模块: 如tf.layers, tf.metrics, 和tf.losses,使得代码稍微有些简化。 任务:花卉分类 版本:tenso...

python字符串连接方式汇总

在python中有很多字符串连接方式,今天就在这里具体总结一下: ①.最原始的字符串连接方式:str1 + str2 ②.python 新字符串连接语法:str1, str2 ③.奇怪的...

创建pycharm的自定义python模板方法

在pycharm上依次选择打开File->settings->Editor->File andCode Templates->Python Script 复制以下...