2018年3月9日 星期五

[Python] 第五篇--字典(dictionary)

[Python] 第五篇--字典(dictionary)


1. 建立字典

---方法一---
dict1 = {"蘋果":20, "香蕉":15, "西瓜":50}

---方法二---
dict2 = dict([["蘋果",20],["香蕉",15],["西瓜",50]])

---方法三---
dict3 = dict(蘋果=20, 香蕉=15, 西瓜=50)
注:鍵(key)不能使用數值

2. 字典取值

2.1 當字典重複時
dict1 = {"蘋果":20, "香蕉":15, "西瓜":50, "香蕉":100}
print(dict1["香蕉"])
注:

輸出:
100

2.2 當字典的鍵不存在時
#使用此方法,如果值不存在會造成錯誤
dict1 = {"蘋果":20, "香蕉":15, "西瓜":50}
print(dict1["鳳梨"])

#使用此方法,預設值可有可無,即使鍵不存在於字典中,也可以避免產生錯誤
dict1 = {"蘋果":20, "香蕉":15, "西瓜":50}
#沒有傳入預設值的情況下
print(dict1.get("蘋果"))  #鍵存在於字典時,輸出字典裡的值(20)
print(dict1.get("鳳梨"))  #鍵不存在於字典時,輸出(None)
#有傳入預設值的情況下,鍵不存在於字典中,會輸出預設值
print(dict1.get("蘋果", 80))  #鍵存在於字典時,輸出字典裡的值(20)
print(dict1.get("鳳梨", 75))  #鍵不存在於字典時,輸出預設值(75)

輸出:
20
None
20
75


沒有留言:

張貼留言