在pythonin the dictionary object,You can use the key name to get the key value directly,像這樣:
>>> d = {
"x":1,"y":2}
>>> d["x"]
1
>>> d["y"]
2
>>>
But if the key name does not exist,則會報錯:
>>> d["z"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
This affects the executable of the code.不過可以使用get方法或者setdefaultmethod to avoid this error,The role of both methods is to get the key value of the key,如果鍵存在於字典中,則返回鍵值;If the key does not exist in the dictionary,則返回一個默認值(這個值默認是None,But you can set it yourself),如下:
d = {
"x":1, "y":2}
print(d.get("z"))
print(d.get("z",9))
輸入結果如下:
None
9
可以看到,“z“This key does not exist in the dictionary,使用get方法獲取時,就返回了None,第二次使用get方法時,The default value returned is set 9 .setdefault方法也是一樣的.
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441 尋找有志同道合的小伙伴,互幫互助,群裡還有不錯的視頻學習教程和PDF電子書! '''
d = {
"x":1, "y":2}
print(d.setdefault("z"))
print(d.setdefault("z",9))