1、遍历key值
>>> d = {'Python':'astonishing', 'C++':'complicated', 'Java':'versatile'} >>> for key in d: ... print(key + ':' + d[key]) ... Python:astonishing C++:complicated Java:versatile
同理,可把下列代码的d改为d.keys()
notice:python2除了上述两种方法外,还可以写为d.iterkeys()
2、遍历value值
>>> for value in d: ... print(value) ... Python C++ Java
同理,可把下列代码的d改为d.values()
notice:python2除了上述两种方法外,还可以写为d.itervalues()
3、遍历字典
>>> for kv in d.items(): ... print(kv) ... ('Python', 'astonishing') ('C++', 'complicated') ('Java', 'versatile') >>> for k, v in d.items():#开始偷懒,缩写k, v ... print(k + ':' + v) ... Python:astonishing C++:complicated Java:versatile
其实还有一种方法,用到了zip(元素对)使得我们可以像c/c++等语言一样循环两个变量。
>>> for k, v in zip(d.keys(), d.values()): ... print(k + ':' + v) ... Python:astonishing C++:complicated Java:versatile
关于zip的用法,详见python cookbook:https://python3-cookbook.readthedocs.io/zh_CN/latest/c04/p11_iterate_over_
multiple_sequences_simultaneously.html
python学习网,大量的免费python视频教程,欢迎在线学习!