甲居工作室

5.Python 字典(Dictionary)

日期:2024/04/06

5.Python 字典(Dictionary)

Python 字典是一種無序、可變 (Mutable)的容器。字典由一對大括號 {} 構成,每組 (item) 的鍵 (key)值 (value)之間用冒號 : 分隔,每組之間用逗號 , 分隔。例如:

  1. user = {'name': 'John', 'age': 30, 'city': '臺中'}

本章將開始介紹字典相關的方法 (method)、函式(function)與操作。

5.1 字典操作

建立字典

鍵必須是唯一的且不可變的(如字串、數字或元組),而值可以是任意類型的(包括串列、字典等)。

  • 使用大刮號 {}
    1. dict1 = {} # 空字典
    2. dict1_2 = {'one':1, 'tow':2, 'three': 3} # 直接賦值
  • 使用內建函數 dict()
    1. dict2 = dict() # 空字典
    2. dict2_1 = dict(one=1, two=2, three=3) # 使用關鍵字參數的方式創建了一個字典
    3. dict2_2 = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 使用 zip() 函式將兩個列表合併後,再將結果轉換成字典
    4. dict2_3 = dict([('one', 1), ('two', 2), ('three', 3)]) # 使用包含鍵與值的元組的列表來創建字典

dict1_2dict2_1dict2_2dict2_3輸出皆是一樣的。

  1. {'one': 1, 'two': 2, 'three': 3}

存取字典元素

先宣告一個字典如下。

  1. grades = {'Alice': 85, 'Bob': 72, 'Charlie': 90}
  • 利用方括號
    1. print(grades['Alice'])
    2. # 85
    3. print(grades['John'])
    4. # KeyError: 'John'
  • 利用 .get() 方法
    1. print(grades.get('Alice'))
    2. # 85
    3. print(grades.get('John'))
    4. # None

有看出兩者主要區別嗎?
使用方括號時,若找不到鍵值程式會輸出錯誤 KeyErrors (鍵值錯誤)。
使用 .get() 方法時,若找不到鍵值程式不會輸出錯誤 ,會回傳None
我們也可指定預設值,如下:

  1. print(grades.get('John', 60))
  2. # 60

修改字典元素

  1. grades['Alice'] = 88
  2. print(grades)
  3. # {'Alice': 88, 'Bob': 72, 'Charlie': 90}
  4. grades.update({'Bob':70})
  5. print(grades)
  6. # {'Alice': 88, 'Bob': 70, 'Charlie': 90}
  7. grades.update({'Bob':60, 'Charlie':80})
  8. print(grades)
  9. # {'Alice': 88, 'Bob': 60, 'Charlie': 80}

添加字典元素

  1. grades['Max'] = 75
  2. print(grades)
  3. # {'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Max': 75}
  4. grades.update({'Nelson':100, 'Edward':99})
  5. print(grades)
  6. #{'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Max': 75, 'Nelson': 100, 'Edward': 100}

刪除字典元素

  1. del grades['Max']
  2. print(grades)
  3. # {'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Nelson': 100, 'Edward': 100}

字典相關方法

方法描述
dict.keys()返回字典中所有鍵
dict.values()返回字典中所有值
dict.items()返回字典中所有鍵-值對
dict.get(key, default=None)返回指定鍵對應的值,如果鍵不存在,則返回預設值

5.2 回家作業

題目描述:

設計一個程式,根據使用者輸入的季節名稱,將其中文翻譯為英文,或英文翻譯為中文 (春天:spring, 夏天:summer, 秋天:fall, 冬天:winter)。

要求:

1.提示使用者輸入季節名稱(中文或英文)。

  1. 根據輸入的季節名稱,將其翻譯為另一種語言。
  2. 顯示翻譯結果。
  3. 請使用字典。

延伸閱讀

6.Python 邏輯判斷 (if、elif、else / match、case)

邏輯判斷 (if、elif、else / match、case)

Read more

7.Python迴圈 (for loop / while loop)

在Python中,for 迴圈是一種用於迭代序列(如列表、元組或字串)或其他可迭代對象(如字典)中的元素的迭代工具。它能夠按照指定的順序遍歷容器中的元素,並在每次迭代中執行特定的操作。

Read more