1.使用 for key in dict遍歷字典
可以使用for key in dict
遍歷字典中所有的鍵
1
2
3
4
5
6
7
8
|
x = { 'a' : 'A' , 'b' : 'B' } for key in x: print (key) # 輸出結果 a b |
2.使用for key in dict.keys () 遍歷字典的鍵
字典提供了 keys ()
方法返回字典中所有的鍵
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# keys book = { 'title' : 'Python' , 'author' : '-----' , 'press' : '人生苦短,我用python' } for key in book.keys(): print (key) # 輸出結果 title author press |
3.使用 for values in dict.values () 遍歷字典的值
字典提供了 values ()
方法返回字典中所有的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' # values book = { 'title' : 'Python' , 'author' : '-----' , 'press' : '人生苦短,我用python' } for value in book.values(): print (value) # 輸出結果 Python - - - - - 人生苦短,我用python |
4.使用 for item in dict.items () 遍歷字典的鍵值對
字典提供了 items ()
方法返回字典中所有的鍵值對 item
鍵值對 item
是一個元組(第 0 項是鍵、第 1 項是值)
1
2
3
4
5
6
7
8
9
10
|
x = { 'a' : 'A' , 'b' : 'B' } for item in x.items(): key = item[ 0 ] value = item[ 1 ] print ( '%s %s:%s' % (item, key, value)) # 輸出結果 ( 'a' , 'A' ) a:A ( 'b' , 'B' ) b:B |
5.使用 for key,value in dict.items () 遍歷字典的鍵值對
元組在 = 賦值運算符右邊的時候,可以省去括號
1
2
3
4
5
6
7
8
9
10
11
|
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' item = ( 1 , 2 ) a, b = item print (a, b) # 輸出結果 1 2 |
例:
1
2
3
4
5
6
7
8
|
x = { 'a' : 'A' , 'b' : 'B' } for key, value in x.items(): print ( '%s:%s' % (key, value)) # 輸出結果 a:A b:B |
到此這篇關于Python字典 dict幾種遍歷方式的文章就介紹到這了,更多相關Python 字典 dict內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/python960410445/p/15510522.html