Python编程:从入门到实践(第二版)随书敲代码 第六章 字典
alien.py
# 第六章 字典
# 6.1 一个简单的字典
alien_0 = {'color': 'green', 'points': '5'}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print(f"\nYou just earned {new_points} points!")
print("\n")
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
print("\n")
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
print("\n")
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
print("\n")
alien_0 = {'x_position': 0,'y_position': 25,'speed':'medium'}
print(f"Original x_position: {alien_0['x_position']}")
# 向右移动外星人
# 根据当前速度确定将外星人向右移动多远。
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
#这个外星人的移动速度肯定很快
x_increment = 3
# 新位置为旧位置加上移动距离。
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New x_position: {alien_0['x_position']}")
print("\n")
alien_0 = {'color': 'green','points': '5'}
print(alien_0)
del alien_0['points']
print(alien_0)
favorite_languages.py
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
print("\n")
# 遍历所有键值对items()
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
print("\n")
# 遍历字典中的所有键keys()
for name in favorite_languages.keys():
print(name.title())
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language.title()}!")
print("\n")
# 使用keys()检查是否存在
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")
print("\n")
# 按特定顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, Thank you taking the poll.")
print("\n")
# 遍历字典中的所有值
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
print("\n")
# 剔除重复项,使用set集合
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
alien_no_points.py
alien_0 = {'color':'green','speed':'slow'}
#键值错误
#print(alien_0['points'])
#使用get()指定键值
point_value = alien_0.get('points','No point value assigned.')
print(point_value)
person.py
# 练习 6-1 人
# 使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。
# 该字典应包含键 first_name 、last_name 、age 和 city 。将存储在该字典中的每项信息都打印出来。
person = {
'first_name': 'yutada',
'last_name': 'hikaru',
'age': '28',
'city': 'tokyo',
}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
favorite_numbers1.py
#练习 6-2 喜欢的数
#使用一个字典来存储一些人喜欢的数。请想出 5 个人的名字,并将这些名字用作字典中的键;
#想出每个人喜欢的一个数,并将这些数作为值存储在字典中。打印每个人的名字和喜欢的数。
#为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_numbers = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
}
number = favorite_numbers['a']
print(f"a's favorite number is {number}.")
number = favorite_numbers['b']
print(f"b's favorite number is {number}.")
number = favorite_numbers['c']
print(f"c's favorite number is {number}.")
number = favorite_numbers['d']
print(f"d's favorite number is {number}.")
number = favorite_numbers['e']
print(f"e's favorite number is {number}.")
glossary.py
# 练习 6-3 词汇表
# Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
# 想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
# 以整洁的方式打印每个词汇及其含义。为此,可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;
# 也可在一行打印词汇,再使用换行符( \n )插入一个空行,然后在下一行以缩进的方式打印词汇的含义。
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
}
#第一种方法
word = 'string'
print(f"\n{word.title()}: {glossary[word]}")
word = 'comment'
print(f"\n{word.title()}: {glossary[word]}")
word = 'list'
print(f"\n{word.title()}: {glossary[word]}")
word = 'loop'
print(f"\n{word.title()}: {glossary[word]}")
word = 'dictionary'
print(f"\n{word.title()}: {glossary[word]}")
#第二种使用for遍历简写
for k,v in glossary.items():
print(f"\n{k.title()}: {v}")
glossary1.py
# 练习 6-4 词汇表 2
# 现在你知道了如何遍历字典,请整理你为完成练习 6-3 而编写的代码,将其中的一系
# 列函数调用 print()替换为一个遍历字典中键和值的循环。
# 确定该循环正确无误后,再在词汇表中添加 5 个 Python 术语。
# 当你再次运行这个程序时,这些新术语及其含义将自动包含在输出中。
glossary = {
'string': 'A series of characters.',
'comment': 'A note in a program that the Python interpreter ignores.',
'list': 'A collection of items in a particular order.',
'loop': 'Work through a collection of items, one at a time.',
'dictionary': "A collection of key-value pairs.",
'key': 'The first item in a key-value pair in a dictionary.',
'value': 'An item associated with a key in a dictionary.',
'conditional test': 'A comparison between two values.',
'float': 'A numerical value with a decimal component.',
'boolean expression': 'An expression that evaluates to True or False.',
}
for word,definition in glossary.items():
print(f"{word.title()}: {definition}")
rivers.py
# 练习 6-5 河流
# 创建一个字典,在其中存储三条大河流及其流经的国家。
# 其中一个键值对可能是'nile': 'egypt' 。
# 使用循环为每条河流打印一条消息,如 The Nile runs through Egypt。
# 使用循环将该字典中每条河流的名字都打印出来。
# 使用循环将该字典包含的每个国家的名字都打印出来。
rivers = {
'nile': 'egypt',
'mississippi': 'united states',
'fraser': 'canada',
'kuskokwim': 'alaska',
'yangtze': 'china',
}
for river,country in rivers.items():
print(f"The {river.title()} runs through {country.title()}.")
print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
print(f"- {river.title()}")
print("\nThe following countries are included in this data set:")
for country in rivers.values():
print(f"- {country.title()}")
favorite_languages1.py
# 练习 6-6 调查
# 在 6.3.1 节编写的程序 favorite_languages.py 中执行以下操作。
# 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
# 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。
# 对于还未参与调查的人,打印一条消息邀请他参与调查。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name,language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
print("\n")
coders = ['phil','josh','david','becca','sarah','matt','danielle']
for coder in coders:
if coder in favorite_languages.keys():
print(f"Thank you for taking the poll, {coder.title()}!")
else:
print(f"{coder.title()},what's your favorite programming language?")
aliens.py
alien_0 = {'color': 'green','points': 5}
alien_1 = {'color': 'yellow','points': 10}
alien_2 = {'color': 'red','points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
print("\n")
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green','points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 修改前三个外星人
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
# 显示前5个外星人
for alien in aliens[:5]:
print(alien)
print("...")
# 显示创建了多少个外星人
print(f"Total number of aliens: {len(aliens)}")
pizza.py
# 存储所点比萨的信息
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨。
print(f"You ordered a {pizza['crust']}-crust pizza"
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
favorite_languages2.py
favorite_languages = {
'jen': ['python','ruby'],
'sarah': ['c'],
'edward': ['python','haskell'],
}
for name, languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
many_users.py
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie':{
'first':'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername:{username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
people.py
# 练习 6-7 人们
# 在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典,
# 然后将这三个字典都存储在一个名为 people 的列表中。
# 遍历这个列表,将其中每个人的所有信息都打印出来。
# 创建一个用于存储人的空列表。
people = []
# 定义一些人并将他们添加到前述列表中。
person = {
'first_name': 'eric',
'last_name': 'matthes',
'age': 46,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'lemmy',
'last_name': 'matthes',
'age': 2,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'willie',
'last_name': 'matthes',
'age': 11,
'city': 'sitka',
}
people.append(person)
# 显示列表包含的每个字典中的信息。
for person in people:
name = f"{person['first_name'].title()} {person['last_name'].title()}"
age = person['age']
city = person['city'].title()
print(f"{name}, of {city}, is {age} year old.")
pets.py
# 练习 6-8 宠物
# 创建多个字典,对于每个字典,都将宠物的名称包含在字典;
# 在每个字典中,包含宠物的类型及其主人的名字。
# 将这些字典存储在一个名为 pets 的列表中,再遍历该列表,
# 并将有关每个宠物的所有信息都打印出来。
# 创建一个用于存储宠物的空列表。
pets = []
# 定义各个宠物并将其存储到列表中。
pet = {
'animal type': 'python',
'name': 'john',
'owner': 'guido',
'weight': 43,
'eats': 'bugs',
}
pets.append(pet)
pet = {
'animal type': 'chicken',
'name': 'clarence',
'owner': 'tiffany',
'weight': 2,
'eats': 'seeds',
}
pets.append(pet)
pet = {
'animal type': 'dog',
'name': 'peso',
'owner': 'eric',
'weight': 37,
'eats': 'shoes',
}
pets.append(pet)
# 打印每个宠物信息
for pet in pets:
print(f"\nHere's what I know about {pet['name'].title()}:")
for k, v in pet.items():
print(f"\t{k}: {v}")
favorite_places.py
# 练习 6-9 喜欢的地方
# 创建一个名为 favorite_places 的字典。在这个字典中,将三个人的名字用作键;
# 对于其中的每个人,都存储他喜欢的 1~3 个地方。
# 为让这个练习更有趣些,让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
'eric': ['bear mountain', 'death valley', 'tierra del fuego'],
'erin': ['hawaii', 'iceland'],
'willie': ['mt. verstovia', 'the playground', 'new hampshire'],
}
for name,places in favorite_places.items():
print(f"\n{name.title()} like the following places:")
for place in places:
print(f"- {place.title()}")
favorite_numbers2.py
# 练习 6-10 喜欢的数 2
# 修改为完成练习 6-2 而编写的程序,让每个人都可以有多个喜欢的数,
# 然后将每个人的名字及其喜欢的数打印出来。
favorite_numbers = {
'mandy': [42, 17],
'micah': [42, 39, 56],
'gus': [7, 12],
}
for name, numbers in favorite_numbers.items():
print(f"\n{name.title()} like the following numbers:")
for number in numbers:
print(f" {number}")
cities.py
# 练习 6-11 城市
# 创建一个名为 cities 的字典,在其中将三个城市名用作键;
# 对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。
# 在表示每座城市的字典中,应包含 country 、population 和 fact 等键。
# 将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'santiago': {
'country': 'chile',
'population': 6_310_000,
'nearby mountains': 'andes',
},
'talkeetna': {
'country': 'united states',
'population': 876,
'nearby mountains': 'alaska range',
},
'kathmandu': {
'country': 'nepal',
'population': 975_453,
'nearby mountains': 'himilaya',
}
}
for city, city_info in cities.items():
country = city_info['country'].title()
population = city_info['population']
mountains = city_info['nearby mountains'].title()
print(f"\n{city.title()} is in {country}.")
print(f" It has a population of about {population}.")
print(f" The {mountains} mountains are nearby.")
Python编程:从入门到实践(第二版)随书敲代码 第六章 字典相关推荐
- 《Python编程从入门到实践 第二版》第十八章练习
18-2:简短的条目 当前,Django在管理网站或shell中显示Entry 实例时,模型Entry 的方法__str__() 都在其末尾加上省略号.请在方法__str__() 中添加一条if 语句 ...
- python编程从入门到实践第二版答案(第三章)
3-1 names = ['day', 'lxd', 'wzy', 'zzz'] print(names[0]) print(names[1]) print(names[2]) print(names ...
- 《Python编程从入门到实践 第二版》第九章练习
9-1 餐馆 创建一个名为Restaurant 的类,为其方法__init__() 设置属性restaurant_name 和cuisine_type.创建一个名为describe_restauran ...
- 《Python编程从入门到实践 第二版》第七章练习
7-1 汽车租赁 编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,下面是一个例子. Let me see if I can find you a Subaru. car = input('W ...
- 学习笔记 | Python编程从入门到实践 | 第二章变量和简单数据类型
前言 小白记录自己学习python的学习贴,如有错误请大佬指正 第二章是变量和简单数据类型的学习. 关于变量 在程序中随时可以修改变量的值,python将始终记录变量的最新值 变量名只能包含字母.数字 ...
- Python编程:从入门到实践-第二章:变量和简单数据(语法)
#2-1 简单消息:将一条消息存储到变量中,再将其打印出来. bian='Hello Python' print(bian) #2-2 多条简单消息:将一条消息存储到变量中,将其打印出来:再将变量的值 ...
- python编程:从入门到实践 外星人入侵项目:武装飞船 代码运行不显示飞船
我的飞船去哪了???!!! 照着书上的项目完整的代码运行一下,结果屏幕上没出现飞船,代码都是对的呀,这是咋回事? 屏幕高度问题 class Settings():"""A ...
- cmd 系统找不到指定路径的问题(Python编程从入门到实践1.5.1踩坑)
对于系统找不到指定路径的问题 大同小异 啊 我是一名Python初学者 在学习Python编程从入门到实践(第二版) 1.5.1在Windows系统中从终端运行Python程序 遇到了这种问题 我是按 ...
- 《Python编程 从入门到实践》简单读书笔记
目录 第2章 变量和简单数据类型 第3章 列表简介 第4章 操作列表 第5章 if语句 第6章 字典 第7章 用户输入和while循环 第8章 函数 第9章 类 第10章 文件和异常 第11章 测试代 ...
最新文章
- QT的QTechnique类的使用
- 安装ORACLE RAC时,用到的一些小命令1.弹出CD,2:配置时间同步,3.查看磁盘信息UUID
- TabControl控件和TabPage的使用
- js 计算对象数组中某个属性值重复出现的个数
- ASP.NET MVC 使用 Datatables (1)
- 金笛JDMail邮件系统从源头上为企业铸造防lj邮件墙--4
- 答案对程序不对matlab,程序结果不对
- Linux实验室 CentOS关机大法
- 觉得做人累了就看看这些!不是社会错了,是你错了!写的超好!
- MySQL error(2006) server has gone away
- uva 1585 Score(Uva-1585)
- myeclipse 创建 maven项目的时候出现:invalid project description 解决方法
- 普元EOS:执行自定义命名sql查询(无参,有参)
- 手动剿灭Word宏病毒
- MATLAB 符号运算
- 好系统帮你恢复win7经典开机画面
- 抽象类是不是必须要有抽象方法
- PowerDesigner根据数据库生成数据字典
- 阳光/海浪/沙滩/美女/泳装——51CTO.com两周年出游
- 工业视觉_57:霍夫(Hough)直线识别,交点与夹角
热门文章
- python11——模块与包
- Codewars一些积累No.3 从罗马数字编码器来初探string的实用用法
- 黑板简笔画说课通用PPT模板
- PHPExcel设置默认列宽
- cURL error 1014: SSL verify failed
- WIFi天线和天线测试
- 行业分析-全球与中国数字农业软件市场现状及未来发展趋势
- 计算机毕设(附源码)JAVA-SSM敬老院信息管理系统
- 如何更改Windows显示字体_更改系统字体
- Overcoming Classifier Imbalance for Long-tail Object Detection with Balanced Group Softmax(CVPR20)