Home  >  Article  >  Backend Development  >  在Python中用get()方法获取字典键值的教程

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

WBOY
WBOYOriginal
2016-06-06 11:17:191300browse

 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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn