Python3实现的字典遍历操作详解
程序员文章站
2022-04-01 20:02:14
...
这篇文章主要介绍了Python3实现的字典遍历操作,结合实例形式分析了Python3针对字典键、键值及键值对遍历的相关操作技巧,需要的朋友可以参考下
本文实例讲述了Python3字典遍历操作。分享给大家供大家参考,具体如下:
字典是针对非序列集合而提供的一种数据类型。
通过任意键查找集合中值信息的过程叫映射,python通过字典实现映射。
为字典赋值:
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> print(d) {1: 123, 'list': [1, 2, 3], '111': 'python3', 'tuple': (4, 5, 6)}
以上语句说明,字典中各项的顺序与赋值时的顺序可能不一致,即字典是无序的。
字典的遍历有一下几种:
1. 遍历字典的键key
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d: print(str(key)+':'+str(d[key])) list:[1, 2, 3] 1:123 111:python3 tuple:(4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d.keys(): print(key) 1 list 111 tuple
2. 遍历字典的值value
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for value in d.values(): print (value) [1, 2, 3] 123 python3 (4, 5, 6)
3. 遍历字典的项
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for item in d.items(): print(item) ('list', [1, 2, 3]) (1, 123) ('111', 'python3') ('tuple', (4, 5, 6))
4. 遍历字典的key-value
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key,value in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for (key,value) in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
上述示例运行效果如下图所示:
相关推荐:
以上就是Python3实现的字典遍历操作详解的详细内容,更多请关注其它相关文章!