在Python中用get()方法获取字典键值的教程

yipeiwu_com6年前Python基础

 get()方法返回给定键的值。如果键不可用,则返回默认值None。
语法

以下是get()方法的语法:

dict.get(key, default=None)

参数

  •     key -- 这是要搜索在字典中的键。
  •     default -- 这是要返回键不存在的的情况下默认值。

返回值

该方法返回一个给定键的值。如果键不可用,则返回默认值为None。
例子

下面的例子显示了get()方法的使用。

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 27}

print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Sex', "Never")

当我们运行上面的程序,它会产生以下结果:

Value : 27
Value : Never

相关文章

python操作mysql数据库

一、数据库基本操作 1. 想允许在数据库写中文,可在创建数据库时用下面命令 create database zcl charset utf8; 2. 查看students表结构 desc...

《Python之禅》中对于Python编程过程中的一些建议

《Python之禅》中对于Python编程过程中的一些建议

围绕一门语言,学习它的文化精髓,能让你成为一名更优秀的程序员。如果你还没读过Python之禅(Zen of Python) ,那么打开Python的命令提示符输入import this,...

Python3之读取连接过的网络并定位的方法

如下所示: #!/usr/bin/python # coding=utf-8 import json from urllib.request import urlopen from...

在python中使用正则表达式查找可嵌套字符串组

在网上看到一个小需求,需要用正则表达式来处理。原需求如下: 找出文本中包含”因为……所以”的句子,并以两个词为中心对齐输出前后3个字,中间全输出,如果“因为”和“所以”中间还存在“因为”...

pytorch:torch.mm()和torch.matmul()的使用

如下所示: torch.mm(mat1, mat2, out=None) → Tensor torch.matmul(mat1, mat2, out=None) → Tensor...