如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
aDict = { 'key1' : 'value1' , 'key2' : 'value2' , 'key3' : 'value3' }
print '-----------dict-------------'
for d in aDict:
print "%s:%s" % (d, aDict[d])
print '-----------item-------------'
for (k,v) in aDict.items():
print '%s:%s' % (k, v)
#效率最高
print '------------iteritems---------'
for k,v in aDict.iteritems():
print '%s:%s' % (k, v)
#最笨的方法
print '---------iterkeys---------------'
for k in aDict.iterkeys():
print '%s:%s' % (k, aDict[k])
print '------------iterkeys, itervalues----------'
for k,v in zip (aDict.iterkeys(), aDict.itervalues()):
print '%s:%s' % (k, v)
|
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
key3:value3
key2:value2
key1:value1
- - - - - - - - - - - item - - - - - - - - - - - - -
key3:value3
key2:value2
key1:value1
- - - - - - - - - - - - iteritems - - - - - - - - -
key3:value3
key2:value2
key1:value1
- - - - - - - - - iterkeys - - - - - - - - - - - - - - -
key3:value3
key2:value2
key1:value1
- - - - - - - - - - - - iterkeys, itervalues - - - - - - - - - -
key3:value3
key2:value2
key1:value1
|
以上这篇遍历python字典几种方法总结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。