- Python王者归来
- 洪锦魁
- 840字
- 2020-08-28 21:54:53
9-2 遍历字典
大型程序设计中,字典用久了会产生相当数量的元素,也许是几千个或几十万个或更多。本节将说明如何遍历字典的键-值对、键或值。
9-2-1 遍历字典的键-值
Python有提供方法items( ),可以让我们取得字典键-值配对的元素,若是以ch9_16.py的players字典为实例,可以使用for循环加上items( )方法,如下所示:

上述只要尚未完成遍历字典,for循环将持续进行,如此就可以完成遍历字典,同时传回所有的键-值。
程序实例ch9_17.py:列出players字典所有元素,相当于所有球员数据。

执行结果

上述实例的执行结果中虽然元素出现顺序与程序第2行到第6行的顺序相同,不过读者须了解Python的直译器并不保证未来一定会保持相同顺序,因为字典(dict)是一个无序的数据结构,Python只会保持键-值,不会关注元素的排列顺序。
9-2-2 遍历字典的键
有时候我们不想要取得字典的值(value),只想要键(keys),Python有提供方法keys( ),可以让我们取得字典的键内容,若是以ch9_16.py的players字典为实例,可以使用for循环加上keys( )方法,如下所示:

上述for循环会依次将players字典的键传回。
程序实例ch9_18.py:列出players字典所有的键(keys),此例是所有球员名字。

执行结果

其实上述实例第7行也可以省略keys( )方法,而获得一样的结果,未来各位设计程序是否使用keys( ),可自行决定,细节可参考ch9_19.py的第7行。
程序实例ch9_19.py:重新设计ch9_18.py,此程序省略了keys( )方法,但增加一些输出问候语句。

执行结果

9-2-3 排序与遍历字典
Python的字典功能并不会处理排序,如果想要遍历字典同时列出排序结果,可以使用方法sorted( )。
程序实例ch9_20.py:重新设计程序实例ch9_19.py,但是名字将以排序方式列出结果,这个程序的重点是第7行。

执行结果

9-2-4 遍历字典的值
Python有提供方法values( ),可以让我们取得字典值列表,若是以ch9_16.py的players字典为实例,可以使用for循环加上values( )方法,如下所示:
程序实例ch9_21.py:列出players字典的值列表。

执行结果

上述Golden State Warriors重复出现,在字典的应用中键不可有重复,值是可以重复,如果你希望所列出的值不要重复,可以使用集合(set)观念使用set( )函数,例如将第7行改为下列所示即可,这个实例放在ch9_21_1.py,读者可自行参考。这是下一章的主题,更多细节将在下一章解说。

下列是执行结果,可以发现Golden State Warriors不重复了。
