溫馨提示×

python字典中items的用法是什么

小億
101
2024-01-17 19:24:38
欄目: 編程語言

在Python字典(dictionary)中,items()是一個方法,用于返回字典中所有鍵值對(key-value pairs)的視圖(view)。具體來說,它返回一個包含元組的列表,每個元組包含字典中的一個鍵和對應的值。

這個方法的用法如下:

dictionary.items()

示例:

student = {'name': 'Alice', 'age': 18, 'grade': 'A'}
items = student.items()
print(items)

輸出:

dict_items([('name', 'Alice'), ('age', 18), ('grade', 'A')])

在上面的示例中,items()方法返回一個名為items的字典視圖(dict_items),其中包含了字典student中的所有鍵值對。注意,字典視圖是動態(tài)的,當字典發(fā)生變化時,字典視圖也會相應地更新。

你可以使用for循環(huán)來遍歷字典中的所有鍵值對:

student = {'name': 'Alice', 'age': 18, 'grade': 'A'}
for key, value in student.items():
    print(key, ':', value)

輸出:

name : Alice
age : 18
grade : A

在上面的示例中,我們使用for循環(huán)遍歷字典student中的所有鍵值對,并分別將鍵賦值給變量key,將值賦值給變量value,然后將它們打印出來。

0