Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
dict():建立字典
語法:
dict() # 空字典
dict(**kwargs) # 用關鍵字參數建立
dict(mapping) # 從映射物件建立
dict(iterable) # 從鍵值對的可迭代物件建立dict() 用來建立一個字典(dictionary)。字典是 Python 最常用的資料結構之一,用「鍵(key): 值(value)」的方式儲存資料,查找速度極快。# 空字典
empty = dict()
print(empty) # {}
# 也可以用字面值
empty2 = {}
print(empty2) # {}各種建立方式
# 用關鍵字參數(最直覺)
user = dict(name="Alice", age=25, city="Taipei")
print(user) # {'name': 'Alice', 'age': 25, 'city': 'Taipei'}
# 從鍵值對的列表
pairs = [("a", 1), ("b", 2), ("c", 3)]
d = dict(pairs)
print(d) # {'a': 1, 'b': 2, 'c': 3}
# 從兩個列表用 zip 配對
keys = ["x", "y", "z"]
values = [10, 20, 30]
d2 = dict(zip(keys, values))
print(d2) # {'x': 10, 'y': 20, 'z': 30}字典的基本操作
d = dict(name="Bob", score=85)
# 存取值
print(d["name"]) # Bob
print(d.get("email")) # None(不存在不會報錯)
# 新增 / 修改
d["email"] = "bob@example.com"
d["score"] = 90
print(d) # {'name': 'Bob', 'score': 90, 'email': 'bob@example.com'}
# 刪除
del d["email"]
print(d) # {'name': 'Bob', 'score': 90}
# 遍歷
for key, value in d.items():
print(f"{key} = {value}")dict 推導式
跟列表推導式類似,字典也有推導式,可以快速建立字典。
# 數字對應平方
squares = {x: x**2 for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 反轉字典的 key 和 value
original = {"a": 1, "b": 2, "c": 3}
reversed_d = {v: k for k, v in original.items()}
print(reversed_d) # {1: 'a', 2: 'b', 3: 'c'}小小綜合例子
# 統計單字出現次數
text = "apple banana apple cherry banana apple"
words = text.split()
# 方法一:手動計數
count = dict()
for word in words:
count[word] = count.get(word, 0) + 1
print(count) # {'apple': 3, 'banana': 2, 'cherry': 1}
# 方法二:用 dict + zip 建立對照表
fruits = ["apple", "banana", "cherry"]
prices = [30, 15, 50]
menu = dict(zip(fruits, prices))
print(menu) # {'apple': 30, 'banana': 15, 'cherry': 50}
# 計算總金額
order = {"apple": 2, "cherry": 1}
total = sum(menu[item] * qty for item, qty in order.items())
print(f"總金額:{total} 元") # 總金額:110 元