python get()函数是怎样的呢?下面就让我们一起来了解一下吧:
get是属于python下的一个函数,在Python字典中get()函数是返回指定键的值,若是值不在字典中则返回默认值。
具体命令的语法格式为:
dict.get(key, default=None)
参数说明:
key 字典中要查找的键。
default 若是指定键的值不存在时,返回该默认值值。
返回值:
返回指定键的值,若是值不在字典中返回默认值None。
参考范例:
1、
>>> dict_name = {}
>>> dict_name.get("name")
>>> dict_name
{}
#设置“name”get出“wangcongying”, 但是打印 dict_name 的时候,字典中没有任何值
>>> dict_name.get("name", "wangcongying")
'wangcongying'
>>> dict_name
{}
2、
>>> dict_name["name"] = "wangcongying"
>>> dict_name
{'name': 'wangcongying'}
>>> dict_name["gender"] = None
>>> dict_name
{'name': 'wangcongying', 'gender': None}
>>> dict_name.get("gender", "male")
>>> dict_name
{'name': 'wangcongying', 'gender': None}
>>> dict_name.get("name", "julia")
'wangcongying'
以上就是小编的分享了,希望能够帮助到大家。
Python字典的 get() 方法及其“默认”参数
# 字典的get()方法及默认参数name_for_userid = { 382: "Alice", 590: "Bob", 951: "Dilbert",}def greeting(userid): return "Hi %s!" % name_for_userid.get(userid, "there")>>> greeting(382)"Hi Alice!">>> greeting(333333)"Hi there!"
当“get()”被调用时,它会检查字典中是否存在给定的键。
如果确实存在,则返回该键的值。
如果它不存在,则返回参数的默认值。