更新於 2024/11/27閱讀時間約 5 分鐘

[Python] Dictionary字典 - 基礎操作

Dictionary(字典) : 是一個可以用來存放不同資料(不同型態)的容器(集合)

每一個元素都是以{鍵(Key):值(Value)}所構成,字典中每個項目都是用","隔開


字典變數名稱 = {鍵(Key):值(Value)}

weights = {"John":80,"Kelly":50}
types = {1:"moniter", 2:"mouse"}


  • Key 鍵 : 不可變的資料型態通常是String(字串)/Integer(整數)
  • Value值 : 任何可變的資料型態都可以


基本操作:

  • 建立Dictionary
  1. 在{}中輸入每個元素的Key-Value
  2. dict()函數
# 1.
weights = {"John":80,"Kelly":50}
types = {1:"moniter", 2:"mouse"}

# 2.
weights = dict(John=80,Kelly=50)
  • 存取Dictionary

[]中傳入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)
  • 新增Dictionary

[]中輸入要新增的Key的名稱,並指派一個Value

weights = {"John":80,"Kelly":50}

weights["Youna"]=40
print(weights)

# ===========Outputs================
# {'John': 80, 'Kelly': 50, 'Youna': 40}
  • 修改Dictionary

[]中輸入要修改的Key的名稱,並指派一個要修改的Value

weights = {"John":80,"Kelly":50}

weights["Kelly"]=40
print(weights)

# ===========Outputs================
# {'John': 80, 'Kelly': 40}
  • 刪除Dictionary

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================
# {}


  • 查找Dictionary

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




分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.