網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

get()函數|python

欄目: IT科技 / 發佈於: / 人氣:3.25W

get是屬於python下的一個函數,在Python字典中get()函數是返回指定鍵的值,若是值不在字典中則返回默認值。

具體命令的語法格式爲:

dict.get(key, default=None)

python get()函數

參數說明:

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

{}

python get()函數 第2張

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'

Tags:Python 函數