本文实例讲述了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)
上述示例运行效果如下图所示:
以上便是,python字典遍历的几种方式。
Python3 字典遍历