當一個dict,我們想取出他的key,value資料項,可以使用下列方法進行迭代走訪dict.items()
#dict.py
dict_1 = dict({"a":1111,"b":2222,"c":3333})
for i in dict_1.items():
print(i[0],i[1])
#dict.py
dict_1 = dict({"a":1111,"b":2222,"c":3333})
for k,v in dict_1.items():
print(k,v)
若只迭代dict的value,可使用dict.values()
#dict.py
dict_1 = dict({"a":1111,"b":2222,"c":3333})
for v in dict_1.values():
print(v)
若要迭代dict的key,可使用dict.keys()或者直接迭代dict
#dict.py
dict_1 = dict({"a":1111,"b":2222,"c":3333})
for k in dict_1:
print(k)
for k in dict_1.keys():
print(k)
dict.items()、dict.keys()、dict.values()會傳回dictionary view,dictionary view是一個可迭代的物件