Python Dictionary (字典)
Dictionary(簡稱 dict)是一種鍵值對 (key-value pair) 的資料結構,用來儲存有關聯性的資料。
建立 Dictionary
使用大括號 {} 並用冒號 : 分隔 key 和 value:
# 建立 dictionary
person = {
"name": "Alice",
"age": 25,
"city": "Taipei"
}
# 空的 dictionary
empty_dict = {}
# 使用 dict() 函數
person = dict(name="Alice", age=25, city="Taipei")
存取元素
person = {"name": "Alice", "age": 25, "city": "Taipei"}
# 使用 key 存取
print(person["name"]) # Alice
print(person["age"]) # 25
# 使用 get() 方法(key 不存在時不會報錯)
print(person.get("name")) # Alice
print(person.get("country")) # None
print(person.get("country", "Unknown")) # Unknown(指定預設值)
使用
[] 存取不存在的 key 會報 KeyError,而 get() 會回傳 None 或指定的預設值。新增和修改元素
person = {"name": "Alice", "age": 25}
# 新增元素
person["city"] = "Taipei"
print(person) # {'name': 'Alice', 'age': 25, 'city': 'Taipei'}
# 修改元素
person["age"] = 26
print(person) # {'name': 'Alice', 'age': 26, 'city': 'Taipei'}
# update() - 一次更新多個元素
person.update({"age": 27, "country": "Taiwan"})
print(person)
刪除元素
person = {"name": "Alice", "age": 25, "city": "Taipei"}
# del - 刪除指定 key
del person["city"]
print(person) # {'name': 'Alice', 'age': 25}
# pop() - 刪除並回傳值
age = person.pop("age")
print(age) # 25
print(person) # {'name': 'Alice'}
# popitem() - 刪除並回傳最後一個元素
person = {"name": "Alice", "age": 25, "city": "Taipei"}
item = person.popitem()
print(item) # ('city', 'Taipei')
print(person) # {'name': 'Alice', 'age': 25}
# clear() - 清空 dictionary
person.clear()
print(person) # {}
檢查 key 是否存在
person = {"name": "Alice", "age": 25}
print("name" in person) # True
print("city" in person) # False
print("city" not in person) # True
Dictionary 長度
person = {"name": "Alice", "age": 25, "city": "Taipei"}
print(len(person)) # 3
遍歷 Dictionary
person = {"name": "Alice", "age": 25, "city": "Taipei"}
# 遍歷 keys
for key in person:
print(key)
for key in person.keys():
print(key)
# 遍歷 values
for value in person.values():
print(value)
# 遍歷 key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
輸出:
name: Alice
age: 25
city: Taipei
取得所有 keys 和 values
person = {"name": "Alice", "age": 25, "city": "Taipei"}
keys = person.keys()
values = person.values()
items = person.items()
print(list(keys)) # ['name', 'age', 'city']
print(list(values)) # ['Alice', 25, 'Taipei']
print(list(items)) # [('name', 'Alice'), ('age', 25), ('city', 'Taipei')]
Dictionary 複製
original = {"a": 1, "b": 2}
# 直接賦值是參考
ref = original
ref["c"] = 3
print(original) # {'a': 1, 'b': 2, 'c': 3}
# 用 copy() 建立副本
original = {"a": 1, "b": 2}
copy = original.copy()
copy["c"] = 3
print(original) # {'a': 1, 'b': 2}
print(copy) # {'a': 1, 'b': 2, 'c': 3}
合併 Dictionary
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
# Python 3.9+ 使用 |
merged = dict1 | dict2
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 使用 ** 解包
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 使用 update()(會修改原 dict)
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Dictionary Comprehension
# 建立數字對應其平方的字典
squares = {x: x ** 2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 加上條件
evens = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(evens) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# 轉換現有的 dictionary
original = {"a": 1, "b": 2, "c": 3}
upper_keys = {k.upper(): v * 2 for k, v in original.items()}
print(upper_keys) # {'A': 2, 'B': 4, 'C': 6}
巢狀 Dictionary
users = {
"user1": {
"name": "Alice",
"age": 25
},
"user2": {
"name": "Bob",
"age": 30
}
}
print(users["user1"]["name"]) # Alice
print(users["user2"]["age"]) # 30
setdefault()
如果 key 存在,回傳其值;如果不存在,設定預設值並回傳:
person = {"name": "Alice"}
# key 存在
result = person.setdefault("name", "Unknown")
print(result) # Alice
print(person) # {'name': 'Alice'}
# key 不存在
result = person.setdefault("age", 25)
print(result) # 25
print(person) # {'name': 'Alice', 'age': 25}