读书笔记 | Python学习之旅 Day15

2018-03-30  本文已影响0人  公子老马

Python学习之旅 读书笔记系列

Day 15

《Python编程从入门到实践》

复盘:第一部分基础知识(第1章~11章)

练习题

第6章 字典

认识字典及其处理方式

1.my_friends.py

初识字典及字典的键-值获取

my_friend = {
    "first_name":"zou","last_name":"jie",
    "age":"32","city":"shenzhen",
    }
#注意冒号在键跟值中间,分行时左右花括号的位置,以及养成习惯最后一组预留”,“
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"]) + ".")
#打印时断行,在合适地方分拆

word_list = {}
word_list["print"] = "打印"
word_list["while"] = "循环"
word_list["if"] = "条件判断"
word_list["range"] = "列表"
word_list["tuple"] = "元组"
print("print:" + word_list["print"])
print("\nwhile:" + word_list["while"])
print("range:" + word_list["range"])
#特别留意换行符在冒号内,且放在换行行的句前

输出结果如下:


2.word_list.py

字典的遍历:键-值对,键,值

word_list = {}
word_list["print"] = "打印"
word_list["while"] = "循环"
word_list["if"] = "条件判断"
word_list["range"] = "列表"
word_list["tuple"] = "元组"
for word, mean in word_list.items():
    """遍历字典中的键-值对"""
    print("\nWord:" + word)
    print("Mean:" + mean)
word_list["sort"] = "排序"
word_list["len"] = "字段长度"
word_list["strip"] = "去除空格"
word_list["string"] = "字符串"
word_list["python_zen"] = "Python之禅"
for word, mean in word_list.items():
    """添加5组数据之后,再遍历字典中的键-值对"""
    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():
    """一起提取键-值对中的键和值, items后面不要忘记括号"""
    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())

输出结果如下:



3.favorite_languages.py

字典与列表的综合运用,范围和条件判断

favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
survey_list = [
    'jen','sarah',
    'jason','edward',
    'smile','phil'
    ]
for name in survey_list:
    """嵌套时,注意字典范围和判断的先后,keys后面小括号不要忘记"""
    if name in favorite_languages.keys():
        print('Thanks for your support!')
    else:
        print('Please help to intend the survey!')

输出结果如下:


其他
上一篇下一篇

猜你喜欢

热点阅读