Python字典遍歷操作實例小結
本文實例講述了Python字典遍歷操作。分享給大家供大家參考,具體如下:
1 遍歷鍵值對
可以使用一個 for 循環(huán)以及方法 items() 來遍歷這個字典的鍵值對。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} for key, value in dict.items(): print('key=' + key) print('value=' + value)
運行結果:
key=evaporation
value=蒸發(fā)
key=carpenter
value=木匠
key、value 這兩個變量可以任意命名,比如下面的這個示例使用了 word 與 explain:
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} for word, explain in dict.items(): print('word=' + word) print('explain=' + explain)
運行結果:
word=evaporation
explain=蒸發(fā)
word=carpenter
explain=木匠
良好的命名習慣,可以編寫出讓人更容易理解的代碼。
2 遍歷鍵
使用方法 keys()
,可以遍歷字典中的鍵。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} for word in dict.keys(): print(word.title())
運行結果:
Evaporation
Carpenter
因為遍歷字典時, 會默認遍歷所有的鍵。所以,我們可以省略方法 keys() 。
for word in dict: print(word.title())
運行結果與上一示例相同。
方法 keys()
還可以用在條件表達式中,用于判斷 key 在字典中是否存在。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} print('carpenter' in dict)
運行結果:
True
3 按順序遍歷鍵
可以在 for
循環(huán)中對返回的鍵進行排序,可以使用 sorted()
函數。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} for word in sorted(dict): print('word:' + word)
運行結果:
word:carpenter
word:evaporation
4 遍歷值
可使用 values()
方法來遍歷字典的值。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠'} for explain in dict.values(): print('explain:' + explain)
運行結果:
explain:蒸發(fā)
explain:木匠
有時候需要返回不重復的值。這時,我們可以使用集合( set) 。 集合類似于列表, 但它所包含的每個元素,都必須是獨一無二的。
dict = {'evaporation': '蒸發(fā)', 'carpenter': '木匠', 'millman': '木匠'} print('【包含重復】' + str(dict.values())) print('【剔除重復】' + str(set(dict.values())))
運行結果:
【包含重復】dict_values(['蒸發(fā)', '木匠', '木匠'])
【剔除重復】{'蒸發(fā)', '木匠'}
**注意:**字典的 values()
的字符串化與 set()
不同。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python字典操作技巧匯總》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
在Mac OS系統(tǒng)上安裝Python的Pillow庫的教程
這篇文章主要介紹了在MacOS下安裝Python的Pillow庫的教程,Pillow庫用來對圖片進行各種處理操作,需要的朋友可以參考下2015-11-11Pytorch中torch.repeat_interleave()函數使用及說明
這篇文章主要介紹了Pytorch中torch.repeat_interleave()函數使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01