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 字典遍历的方法_第1张图片

 

以上便是,python字典遍历的几种方式。

 

你可能感兴趣的:(python3 字典遍历的方法)