Python遍历字典的几种方式

  记录遍历字典的几种方式

 1 #遍历字典key值---方法1
 2 for key in dict1:
 3     print(key)
 4 
 5 # 遍历字典key值---方法2
 6 for key in dict1.keys():
 7     print(key)
 8 
 9 #遍历字典value值
10 for value in dict1.values():
11     print(value)
12 
13 #遍历字典中的元素
14 for item in dict1.items():
15     print(item)

输出结果:

 1 #遍历字典key值---方法1
 2 name
 3 age
 4 native
 5 opus
 6 
 7 #遍历字典key值---方法2
 8 name
 9 age
10 native
11 opus
12 
13 #遍历字典value值
14 吴亦凡
15 29
16 广州
17 大碗宽面
18 
19 #遍历字典中的元素
20 ('name', '吴亦凡')
21 ('age', '29')
22 ('native', '广州')
23 ('opus', '大碗宽面')

猜你喜欢

转载自www.cnblogs.com/wdana/p/12103510.html
今日推荐