描述:Python2.7中如果想要獲取字典中的一個值,但是這個值可能不存在,此時應(yīng)該加上判斷:
舉個例子:
1
2
3
4
5
6
7
|
t = {} if t.get( '1' ): # right:這種通過key來查詢是否存在的方式是比較好的 print (t[ '1' ]) print ( 'right' ) if t[ '1' ]: # wrong:這種直接判斷是否存在的方式因?yàn)闀谂袛嘀罢{(diào)用,所以會報錯 print (t[ '1' ]) |
額外說明:
1
|
|
Parameters:
key -- This is the Key to be searched in the dictionary.
default -- This is the Value to be returned in case key does not exist.
如果default沒指定,而且沒有搜到值的話,會返回None
以上這篇解決Python獲取字典dict中不存在的值時出錯問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qijingpei/article/details/75036027