Python字典遍历

 1 def dict_test():
 2     #初始化字典
 3     dict= {"a1":"1","a2":"2","a3":"3"}
 4 
 5     #遍历Key
 6     print("遍历Key\n")
 7     for key in dict:
 8         print(key+':'+dict[key])
 9     #遍历Key
10     print("遍历Key\n")
11     for key in dict.keys():
12         print(key + ':' + dict[key])
13     #遍历Value
14     print("遍历Value\n")
15     for value in dict.values():
16         print(value)
17     #遍历字典项
18     print("遍历字典项\n")
19     for kv in dict.items():
20         print(kv)
21     #遍历键值对
22     print("遍历键值对\n")
23     for k,v in dict.items():
24         print("k:",k,"v:",v)
25 if __name__ == '__main__':
26     dict_test()

 

posted @ 2021-10-23 20:26  靠谱杨  阅读(155)  评论(0编辑  收藏  举报