时间:2021-07-01 10:21:17 帮助过:38人阅读
本文实例讲述了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实现购物车功能
Python3实现发送QQ邮件功能(文本)_python
以上就是Python3实现的字典遍历操作详解的详细内容,更多请关注Gxl网其它相关文章!