這篇文章主要介紹了Python3實現的字典遍歷操作,結合實例形式分析了Python3針對字典鍵、鍵值及鍵值對遍歷的相關操作技巧,需要的朋友可以參考下
#本文實例講述了Python3字典遍歷操作。分享給大家供大家參考,具體如下:
字典是針對非序列集合而提供的一種資料型態。
透過任意鍵來找出集合中值資訊的過程叫做映射,python透過字典實作映射。
為字典賦值:
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> print(d) {1: 123, 'list': [1, 2, 3], '111': 'python3', 'tuple': (4, 5, 6)}
#以上語句說明,字典中各項的順序與賦值時的順序可能不一致,即字典是無序的。
字典的遍歷有幾個:
1. 遍歷字典的鍵key
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d: print(str(key)+':'+str(d[key])) list:[1, 2, 3] 1:123 111:python3 tuple:(4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d.keys(): print(key) 1 list 111 tuple
2. 遍歷字典的值value
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for value in d.values(): print (value) [1, 2, 3] 123 python3 (4, 5, 6)
#3. 遍歷字典的項目
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for item in d.items(): print(item) ('list', [1, 2, 3]) (1, 123) ('111', 'python3') ('tuple', (4, 5, 6))
4. 遍歷字典的key-value
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key,value in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for (key,value) in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
Python3實作購物車功能
###Python3實作發送QQ郵件功能(文字)_python######### #################以上是Python3實作的字典遍歷操作詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!