Python dict.items() 方法完整教學
更新日期: 2025 年 1 月 6 日
在 Python 中,dict.items()
是一個非常實用的方法,用於從字典中同時取得 鍵 (key) 和 值 (value)。
這篇文章將詳細解釋 dict.items()
的用法、回傳結果、適用場景,以及如何搭配 for
迴圈進行字典的遍歷操作,並附上多種範例與實務應用。
什麼是 dict.items()
?
語法:
dictionary.items()
說明:
dict.items()
會回傳一個 dict_items 物件 (字典項目集合)。dict_items
是一種視圖物件 (view object),可直接用於迴圈中進行遍歷操作。- 每個元素都是一個 tuple (元組),格式為
(key, value)
。
基本使用方式
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
print(my_dict.items())
輸出結果:
dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
解釋:
dict.items()
回傳了一個 dict_items 物件,其中包含了字典中所有的鍵值對。- 每個鍵值對以 tuple (元組) 的形式表示。
使用 for
迴圈搭配 dict.items()
使用 for
迴圈來遍歷字典的所有鍵值對。
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
輸出結果:
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
解釋:
- 在
for
迴圈中,dict.items()
會將每個鍵值對以(key, value)
的形式解構,並將結果傳遞到key
與value
變數中。
動態更新字典後的影響
dict_items
物件是動態的,也就是說,當字典的內容被修改時,dict_items
物件也會即時反映變化。
my_dict = {'a': 1, 'b': 2}
items = my_dict.items()
print("Before modification:", items)
# 修改字典內容
my_dict['c'] = 3
my_dict['a'] = 10
print("After modification:", items)
輸出結果:
Before modification: dict_items([('a', 1), ('b', 2)])
After modification: dict_items([('a', 10), ('b', 2), ('c', 3)])
解釋:
items
物件是動態視圖,會即時反映字典的更動。
只取得字典的鍵或值
取得所有鍵
my_dict = {'name': 'Alice', 'age': 25}
for key in my_dict:
print(f"Key: {key}")
取得所有值
for value in my_dict.values():
print(f"Value: {value}")
總結:dict.items()
使用重點
dict.items()
會回傳一個dict_items
物件,它是可迭代且動態的視圖物件。- 適合用於遍歷整個字典,可以搭配
for
迴圈同時取得鍵與值。 - 動態更新:修改字典時,
dict_items
也會同步更新。
希望這篇文章幫助你更清楚理解 Python 的 dict.items()
方法!如果還有其他疑問,歡迎隨時向我提問 😊