接上节
3.3 按顺序遍历字典中的所有键
上一节我们说到,Python中并不关心字典中的键-值对顺序,只关心键与值之间的关系,因此遍历字典时元素的获取顺序是不可预测的。如果在某些情况下,一定要按特定顺序返回元素要怎么办呢?一种方法是在for循环中对返回的键的顺序进行排序。为此可使用函数sorted()来获取特定顺序排列的键列表的副本:
favorite_college = {
'jen' : 'carnegie mellon' ,
'sarah' : 'mit' ,
'edward' : 'tsinghua' ,
'phil' : 'harvard' ,
}
for name in sorted(favorite_college.keys()):
print(name.title() + ", thank you for accepting the interview.")
for语句本身与其他for语句相同,但是对于方法keys()调用了函数sorted()。这句代码实际上在做这样的操作:①列出字典中所有的键;②对这个列表进行排序(按字母顺序);③遍历这个排序后的列表。最后的输出结果显示,所有被调查者的名字被按照字母顺序排列:
Edward, thank you for accepting the interview.
Jen, thank you for accepting the interview.
Phil, thank you for accepting the interview.
Sarah, thank you for accepting the interview.
3.4 遍历字典中的所有值
如果你需要的是字典中所有的值,那么可以使用方法value()。例如,我们要获取所有被调查者喜欢的大学,而不需要被调查者的姓名,可以这样做:
favorite_college = { 'jen' : 'carnegie mellon' , 'sarah' : 'tsinghua' , 'edward' : 'tsinghua' , 'phil' : 'harvard' , }
print("The follow college have been mentioned:")
①for college in favorite_college.values():
print(college.title())
①处for语句从字典中依次提取出所有的值,并将它们存入变量college中。通过打印这些值就获得了一个列表,其中包含被调查者选择的各种语言:
The follow college have been mentioned:
Carnegie mellon
Tsinghua
Tsinghua
Harvard
我们成功提取了所有的值,但是你也许会发现,这样的操作没有考虑重复项。如果被调查者很多,一定会有很多重复项。为了剔除重复项,可以使用集合(set)。集合类似于列表,但每个元素必须是独一无二的:
favorite_college = { 'jen' : 'carnegie mellon' , 'sarah' : 'tsinghua' , 'edward' : 'tsinghua' , 'phil' : 'harvard' , }
print("The follow college have been mentioned:")
①for college in set(favorite_college.values()):
print(college.title())
通过对包含重复项的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素创建一个集合。①处我们使用了set()来提取favorite_college中不同的语言。
最终的结果是一个不重复的列表,其中包含了被调查者所提及的所有大学:
The follow college have been mentioned:
Harvard
Tsinghua
Carnegie mellon
我们下次再见。