1.遍历key值
1 >>> d = {'Python':'astonishing', 'C++':'complicated', 'Java':'versatile'}
2 >>> for key in d:
3 ... print(key + ':' + d[key])
4 ...
5 Python:astonishing
6 C++:complicated
7 Java:versatile
同理,可把下列代码的d改为d.keys()
notice:python2除了上述两种方法外,还可以写为d.iterkeys()
2.遍历value值
1 >>> for value in d:
2 ... print(value)
3 ...
4 Python
5 C++
6 Java
同理,可把下列代码的d改为d.values()
notice:python2除了上述两种方法外,还可以写为d.itervalues()
3.遍历字典
1 >>> for kv in d.items():
2 ... print(kv)
3 ...
4 ('Python', 'astonishing')
5 ('C++', 'complicated')
6 ('Java', 'versatile')
7 >>> for k, v in d.items():#开始偷懒,缩写k, v
8 ... print(k + ':' + v)
9 ...
10 Python:astonishing
11 C++:complicated
12 Java:versatile
其实还有一种方法,用到了zip(元素对)使得我们可以像c/c++等语言一样循环两个变量
1 >>> for k, v in zip(d.keys(), d.values()):
2 ... print(k + ':' + v)
3 ...
4 Python:astonishing
5 C++:complicated
6 Java:versatile
关于zip的用法,详见python cookbook:https://python3-cookbook.readthedocs.io/zh_CN/latest/c04/p11_iterate_over_multiple_sequences_simultaneously.html