6.Python 邏輯判斷 (if、elif、else / match、case)
邏輯判斷 (if、elif、else / match、case)
甲居工作室日期:2024/04/06
Python 字典是一種無序、可變 (Mutable)的容器。字典由一對大括號 {} 構成,每組 (item) 的鍵 (key)與值 (value)之間用冒號 : 分隔,每組之間用逗號 , 分隔。例如:
user = {'name': 'John', 'age': 30, 'city': '臺中'}

本章將開始介紹字典相關的方法 (method)、函式(function)與操作。
鍵必須是唯一的且不可變的(如字串、數字或元組),而值可以是任意類型的(包括串列、字典等)。
dict1 = {} # 空字典dict1_2 = {'one':1, 'tow':2, 'three': 3} # 直接賦值
dict2 = dict() # 空字典dict2_1 = dict(one=1, two=2, three=3) # 使用關鍵字參數的方式創建了一個字典dict2_2 = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 使用 zip() 函式將兩個列表合併後,再將結果轉換成字典dict2_3 = dict([('one', 1), ('two', 2), ('three', 3)]) # 使用包含鍵與值的元組的列表來創建字典
dict1_2、dict2_1、dict2_2及dict2_3輸出皆是一樣的。
{'one': 1, 'two': 2, 'three': 3}
先宣告一個字典如下。
grades = {'Alice': 85, 'Bob': 72, 'Charlie': 90}
print(grades['Alice'])# 85print(grades['John'])# KeyError: 'John'
print(grades.get('Alice'))# 85print(grades.get('John'))# None
有看出兩者主要區別嗎?
使用方括號時,若找不到鍵值程式會輸出錯誤 KeyErrors (鍵值錯誤)。
使用 .get() 方法時,若找不到鍵值程式不會輸出錯誤 ,會回傳None 。
我們也可指定預設值,如下:
print(grades.get('John', 60))# 60
grades['Alice'] = 88print(grades)# {'Alice': 88, 'Bob': 72, 'Charlie': 90}grades.update({'Bob':70})print(grades)# {'Alice': 88, 'Bob': 70, 'Charlie': 90}grades.update({'Bob':60, 'Charlie':80})print(grades)# {'Alice': 88, 'Bob': 60, 'Charlie': 80}
grades['Max'] = 75print(grades)# {'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Max': 75}grades.update({'Nelson':100, 'Edward':99})print(grades)#{'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Max': 75, 'Nelson': 100, 'Edward': 100}
del grades['Max']print(grades)# {'Alice': 88, 'Bob': 60, 'Charlie': 80, 'Nelson': 100, 'Edward': 100}
| 方法 | 描述 |
|---|---|
dict.keys() | 返回字典中所有鍵 |
dict.values() | 返回字典中所有值 |
dict.items() | 返回字典中所有鍵-值對 |
dict.get(key, default=None) | 返回指定鍵對應的值,如果鍵不存在,則返回預設值 |
設計一個程式,根據使用者輸入的季節名稱,將其中文翻譯為英文,或英文翻譯為中文 (春天:spring, 夏天:summer, 秋天:fall, 冬天:winter)。
1.提示使用者輸入季節名稱(中文或英文)。