Python學(xué)習(xí)之旅 讀書筆記系列
Day 15
《Python編程從入門到實(shí)踐》
復(fù)盤:第一部分基礎(chǔ)知識(shí)(第1章~11章)
練習(xí)題
第6章 字典
認(rèn)識(shí)字典及其處理方式
1.my_friends.py
初識(shí)字典及字典的鍵-值獲取
my_friend = {
"first_name":"zou","last_name":"jie",
"age":"32","city":"shenzhen",
}
#注意冒號(hào)在鍵跟值中間,分行時(shí)左右花括號(hào)的位置,以及養(yǎng)成習(xí)慣最后一組預(yù)留”,“
print(my_friend["first_name"])
print(my_friend["city"].upper())
print(my_friend["last_name"].title())
favorite_number = {}
favorite_number["Jie_zou"] = 8
favorite_number["Wedny_tu"] = 9
favorite_number["Jason_zou"] = 5
favorite_number["Smile_zou"] = 6
favorite_number["Eric_liu"] = 3
print("Jie_zou's favorite number is " + str(favorite_number["Jie_zou"]) + ".")
print("Smile_zou's favorite number is " +
str(favorite_number["Smile_zou"]) + ".")
#打印時(shí)斷行,在合適地方分拆
word_list = {}
word_list["print"] = "打印"
word_list["while"] = "循環(huán)"
word_list["if"] = "條件判斷"
word_list["range"] = "列表"
word_list["tuple"] = "元組"
print("print:" + word_list["print"])
print("\nwhile:" + word_list["while"])
print("range:" + word_list["range"])
#特別留意換行符在冒號(hào)內(nèi),且放在換行行的句前
輸出結(jié)果如下:

2.word_list.py
字典的遍歷:鍵-值對(duì),鍵,值
word_list = {}
word_list["print"] = "打印"
word_list["while"] = "循環(huán)"
word_list["if"] = "條件判斷"
word_list["range"] = "列表"
word_list["tuple"] = "元組"
for word, mean in word_list.items():
"""遍歷字典中的鍵-值對(duì)"""
print("\nWord:" + word)
print("Mean:" + mean)
word_list["sort"] = "排序"
word_list["len"] = "字段長(zhǎng)度"
word_list["strip"] = "去除空格"
word_list["string"] = "字符串"
word_list["python_zen"] = "Python之禪"
for word, mean in word_list.items():
"""添加5組數(shù)據(jù)之后,再遍歷字典中的鍵-值對(duì)"""
print("\nWord:" + word)
print("Mean:" + mean)
river_list = {}
river_list["nile"] = "egypt"
river_list["changjiang"] = "china"
river_list["amazon"] = "america"
for river,country in river_list.items():
"""一起提取鍵-值對(duì)中的鍵和值, items后面不要忘記括號(hào)"""
print("\nThe " + river.title() + "runs through " + country.title() + ".")
for river in river_list.keys():
"""key,value后面記得加s"""
print("\n" + river)
for country in river_list.values():
print("\n" + country.title())
輸出結(jié)果如下:


3.favorite_languages.py
字典與列表的綜合運(yùn)用,范圍和條件判斷
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
survey_list = [
'jen','sarah',
'jason','edward',
'smile','phil'
]
for name in survey_list:
"""嵌套時(shí),注意字典范圍和判斷的先后,keys后面小括號(hào)不要忘記"""
if name in favorite_languages.keys():
print('Thanks for your support!')
else:
print('Please help to intend the survey!')
輸出結(jié)果如下:

其他
- 感受及注意事項(xiàng)
- 如果多行定義字典時(shí),先輸左花括號(hào),下一行記得“縮進(jìn)4個(gè)空格并以逗號(hào)結(jié)尾”,最后一行結(jié)尾時(shí)仍然加上“,”為添加鍵-值做準(zhǔn)備
- 打印時(shí)分行,記得在合適的地方拆分,末尾加上拼接符(+)
- 遍歷時(shí):.item()為鍵-值對(duì),.keys()為鍵,.values()為值,要剔除重復(fù)值時(shí)加上集合set(字典.values())