Dictionary(字典) : 是一個可以用來存放不同資料(不同型態)的容器(集合)
每一個元素都是以{鍵(Key):值(Value)}所構成,字典中每個項目都是用","隔開
字典變數名稱 = {鍵(Key):值(Value)}
weights = {"John":80,"Kelly":50}
types = {1:"moniter", 2:"mouse"}
基本操作:
# 1.
weights = {"John":80,"Kelly":50}
types = {1:"moniter", 2:"mouse"}
# 2.
weights = dict(John=80,Kelly=50)
在[]中傳入Key的名稱
如果需要查找的Key不在Dictionary裡面時,會產生KeyError的例外錯誤
weights = {"John":80,"Kelly":50}
print(weights["Kelly"])
print(weights["Youna"])
# ===========Outputs================
# 50
# KeyError:'Youna'
用items()遍歷 : 將每對Key-Value組成一個元組Tuple,並把這些Tuple放在列表中返回
weights = {"John":80,"Kelly":50}
for weight in weights.items():
print(weight)
# ===========Outputs================
# ('John', 80)
# ('Kelly', 50)
在[]中輸入要新增的Key的名稱,並指派一個Value
weights = {"John":80,"Kelly":50}
weights["Youna"]=40
print(weights)
# ===========Outputs================
# {'John': 80, 'Kelly': 50, 'Youna': 40}
在[]中輸入要修改的Key的名稱,並指派一個要修改的Value
weights = {"John":80,"Kelly":50}
weights["Kelly"]=40
print(weights)
# ===========Outputs================
# {'John': 80, 'Kelly': 40}
del指令 : 在[]中輸入要刪除的Key
weights = {"John":80,"Kelly":50}
del weights["Kelly"] # 刪除'Kelly'的鍵值
print(weights)
del weights # 刪除weights字典
# ===========Outputs================
# {'John': 80}
clear() : 刪除Dictionary中的所有元素
weights = {"John":80,"Kelly":50}
weights.clear()
print(weights)
# ===========Outputs================
# {}
get() : 傳入要找的Key名稱參數,回傳對應的Value
如果Key不存在,回傳None
weights = {"John":80,"Kelly":50}
print(weights.get("John"))
print(weights.get("Frank"))
# ===========Outputs================
# 80
# None
如果Key不存在,回傳指定的value
weights = {"John":80,"Kelly":50}
print(weights.get("John"))
print(weights.get("Frank",-1))
# ===========Outputs================
# 80
# -1