python中对字典元素keys/values/items的遍历

和列表一样,字典也可以用for XXX in YYY: 这样的循环来遍历字典中的额元素,我们先来看YYY,也就是遍历的范围,python中一共有三种遍历的范围方式:keys/values/items,顾名思义,就是对键值、取值已经整个条目的遍历,如果直接用字典的名字作为遍历的范围,我们默认按照key进行遍历,在使用的时候,注意后面要加上圆括号对。我们也可以使用sorted的方法对于遍历的元素进行排序,对set的方法对value进行去重操作。

以下示例代码可以用来展示字典的各种遍历方式:

favorite_languages ={
	'jen'	:'python',
	'sarah'	:'c',
	'edward':'ruby',
	'phil'	:'python'
}
print("***********根据所有key值遍历字典************")
for friend in favorite_languages:
	message = "The favorite language of "+friend.title()+" is "+favorite_languages[friend]
	print(message)
print("***********根据所有key值进行sorted排序后遍历字典************")
for friend in sorted(favorite_languages):
	message = "The favorite language of "+friend.title()+" is "+favorite_languages[friend]
	print(message)
print("***********根据所有value值遍历字典************")
for language in favorite_languages.values():
	print(language)	
print("***********根据所有value值遍历字典并用set去重输出************")
for language in set(favorite_languages.values()):
	print(language)	
print("***********遍历所有键值对************")
for key,value in favorite_languages.items():
	message = "The favorite language of "+key.title()+" is "+value
	print(message)
print("************用变量名遍历所有键值对**************")
for firend,language in favorite_languages.items():
	message = "The favorite language of "+friend.title()+" is "+language
	print(message)

运行之后,我们就可以看到运行结果了

***********根据所有key值遍历字典************
The favorite language of Jen is python
The favorite language of Sarah is c
The favorite language of Edward is ruby
The favorite language of Phil is python
***********根据所有key值排序后遍历字典************
The favorite language of Edward is ruby
The favorite language of Jen is python
The favorite language of Phil is python
The favorite language of Sarah is c
***********根据所有value值遍历字典************
python
c
ruby
python
***********根据所有value值遍历字典并用set去重输出************
python
ruby
c
***********遍历所有键值对************
The favorite language of Jen is python
The favorite language of Sarah is c
The favorite language of Edward is ruby
The favorite language of Phil is python
************用变量名遍历所有键值对**************
The favorite language of Sarah is python
The favorite language of Sarah is c
The favorite language of Sarah is ruby
The favorite language of Sarah is python
[Finished in 0.5s]

你可能感兴趣的:(python基础数据类型)