python信息笔记——字典遍历
程序员文章站
2022-05-19 15:02:00
...
print('遍历所有键-值对')
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi'
}
for key,value in user_0.items():
print("\nKey:"+key)
print("value:"+value)
favorite_language={
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python'
}
for name,language in favorite_language.items():
print(name.title()+"'s favorite language is"+language.title()+".")
print('遍历所有键')
for name in favorite_language:
#因为默认遍历所有键,这里进行简写,全部为for name in favorite_language.key()
#但全写会让代码更容易读
print(name.title())
friends=['phil','sarah']
for name in favorite_language.keys():
print(name.title())
if name in friends:
print("Hi"+name.title()+",I see your favorite language is"+
favorite_language[name].title()+"!")
print("用sorted()顺序遍历")
for name in sorted(favorite_language.keys()):
print(name.title()+",thank you for taking the poll.")
print('遍历值')
for language in favorite_language.values():
print(language.title())
#涉及值很多时,最终列表含有大量重复项,用set剔除重复项
for language in set(favorite_language.values()):
print(language.title())
上一篇: [JavaScript]陈年老代码:自带AI的井字棋游戏
下一篇: python学习笔记——字典