Python遍历字典dict的几种方法

Python遍历字典dict的几种方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-

dict = {"apple": "苹果", "banana": "香蕉", "orange": "桔子"}

print "----------dict----------"
for k in dict:
print "dict[%s] =" % k, dict[k]

print "----------items----------"
for (k, v) in dict.items():
print "dict[%s] =" % k, v

print "----------iteritems----------"
for k, v in dict.iteritems():
print "dict[%s]=" % k, v

print "----------iterkeys,itervalues----------"
for k, v in zip(dict.iterkeys(), dict.itervalues()):
print "dict[%s]=" % k, v

print "----------keys----------"
for k in dict.keys():
print "dict[%s]=" % k, dict[k]

print "----------keys values----------"
keys = dict.keys()
values = dict.values()
for i in range(len(dict)):
print "dict[%s]=" % keys[i], values[i]

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
----------dict----------
dict[orange] = 桔子
dict[apple] = 苹果
dict[banana] = 香蕉
----------items----------
dict[orange] = 桔子
dict[apple] = 苹果
dict[banana] = 香蕉
----------iteritems----------
dict[orange]= 桔子
dict[apple]= 苹果
dict[banana]= 香蕉
----------iterkeys,itervalues----------
dict[orange]= 桔子
dict[apple]= 苹果
dict[banana]= 香蕉
----------keys----------
dict[orange]= 桔子
dict[apple]= 苹果
dict[banana]= 香蕉
----------keys values----------
dict[orange]= 桔子
dict[apple]= 苹果
dict[banana]= 香蕉

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :