python中,字典是一系列的键值对,每个键都与一个值相关联,可以使用键来访问与之相关联的值。
与键相关联的值可以是数字,字符串,列表,字典,任何python对象都可用作字典中的值。
#1.创建一个字典
alien_0 = {'color':'green','points':5}
print(alien_0)#2.添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)#3.修改字典中的值
print("The alien is "+alien_0['color']+".")alien_0['color'] = 'yellow'
print("The alien is now "+alien_0['color']+".")#4.小案例
"""
对一个能够以不同速度移动的外星人的位置进行跟踪,
为此,我们将存储该外星人的当前速度,并据此确定该外星人将向右移动多远
"""alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print("\nOriginal x-positon :"+str(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("New x-position:"+str(alien_0['x_position']))#5.删除键值对:del
del alien_0['speed']
print(alien_0)#6.由类似对象组成的字典,假设要调查很多人,询问他们喜欢的编程语言
"""使用字典存储众多对象的同一种信息"""
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'python',#在最后一个键值对后面也加上逗号,为以后在下一行添加键值对做准备
}print("\nSarah's favorite languages is "+favorite_languages['sarah'].title()+".")#7.遍历字典中的键值对,items返回一个键值对列表
for name ,languanges in favorite_languages.items():print(name.title()+"'s favorite languagr is"+languanges.title()+".")print("")
#8.遍历字典中的键
for name in favorite_languages.keys():print(name.title())#9.按顺序遍历字典中的所有键,并不改变原有的字典中的顺序
for name in sorted(favorite_languages.keys()):print(name.title()+", thank you for taking the poll")#10.遍历字典中的所有值
print("\nThe favorite languages hav been etioned:")
for language in favorite_languages.values():print(language.title())#11.使用set取出重复值
print("\nThe following languages hav been etioned:")
for language in set(favorite_languages.values()):print(language.title())#12.嵌套:将字典存在列表中,或者将列表作为值存在字典中
#字典列表:创建一个外星人列表,每个列表都是一个字典alien_0 = {'color':'green','point':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)#更符合现实的是:外星人不止3个,且每个外星人都是用代码自动生成的#创建一个用于存储外星人的空列表
aliens =[]
#创建30个绿色的外星人
for alien_number in range(30):new_alien = {'color':'green','points':5,'speed':'slow'}aliens.append(new_alien)#显示前5个外星人
for alien in aliens[:5]:print(alien)
print("...")
print("Total number of aliens:"+str(len(aliens)))#我们可以独立的修改每个外星人
for alien in aliens[:3]:if alien['color'] == 'green':alien['color'] = 'yellow'alien['points'] = 10alien['speed'] = 'medium'#显示前五个外星人
for alien in aliens[:5]:print(alien)
print("...")#在字典中存储列表
#使用字典,存储要添加的披萨配料以及其它描述(如:外皮类型)
#存储所点披萨的信息
pizza = {'crust':'thick','toppings':['mudhrooms','extra cheese'],
}#概述所点披萨
print("You ordered a " +pizza['crust']+"-crust pizza "+"with the following toppings:")
for topping in pizza['toppings']:print("\t"+topping)#当字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表,
#例2:调查喜欢的编程语言:一个人可以喜欢多种
favorite_languages = {'jen':['python','ruby'],'sarah':['c'],'edward':['ruby','go'],'phil':['pyhon','haskell'],
}for name,languages in favorite_languages.items():print("\n"+name.title()+"'s favorite languages are:")for language in languages:print("\t"+language.title())#13.在字典中存储字典
"""
有多个网站用户,每个用户都有独特的用户名,可在字典中将用户名作为键
然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名先关联的值
"""
#对每个用户存储:名,姓和居住地
users = {'aeinstein':{'first':'albert','last':'einstein','location':'princeton',},'mcurie':{'first':"marie",'last':'curie','location':'paris',},
}for username,user_info in users.items():print("\nUsernae:"+username)full_name = user_info['first']+" "+user_info['last']location = user_info['location']print("\tFull name:"+full_name.title())print("\tLocation:"+location.title())
输出结果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
The alien is green.
The alien is now yellow.Original x-positon :0
New x-position:2
{'x_position': 2, 'y_position': 25}Sarah's favorite languages is C.
Jen's favorite languagr isPython.
Sarah's favorite languagr isC.
Edward's favorite languagr isRuby.
Phil's favorite languagr isPython.Jen
Sarah
Edward
Phil
Edward, thank you for taking the poll
Jen, thank you for taking the poll
Phil, thank you for taking the poll
Sarah, thank you for taking the pollThe favorite languages hav been etioned:
Python
C
Ruby
PythonThe following languages hav been etioned:
Ruby
C
Python
{'color': 'green', 'point': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens:30
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
You ordered a thick-crust pizza with the following toppings:mudhroomsextra cheeseJen's favorite languages are:PythonRubySarah's favorite languages are:CEdward's favorite languages are:RubyGoPhil's favorite languages are:PyhonHaskellUsernae:aeinsteinFull name:Albert EinsteinLocation:PrincetonUsernae:mcurieFull name:Marie CurieLocation:Paris
通过获取用户输入并学会控制程序的运行实践,可编写出交互式程序
1.提示超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()
2.使用break退出循环:立刻退出while循环,不在运行循环中余下的代码
3.continue:返回到循环开头,并根据条件测试结果决定是否继续执行循环
4避免无限循环
5.使用while循环来处理列表和字典
#1提示超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()
prompt = "If you tell us ho you are ,we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello, "+ name +"!")#2.使用while循环处理列表和字典
"""
for循环是一种遍历列表的有效方式,但是在for循环中不应修改列表,这将导致python难以跟踪其中的元素
要在遍历列表的同时对齐进行修改,可使用while循环
"""#假设一个列表,其中包含寻注册但还未验证的网站用户;
# 使用while循环,在验证这些用户的同时将其从未验证用户列表中提取出来,加入到另一个已验证用户列表中#首先创建一个待验证用户列表和一个存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移动到已验证用户列表中
while unconfirmed_users:current_suer = unconfirmed_users.pop()print("Verifying user:"+current_suer.title())confirmed_users.append(current_suer)#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user.title())#删除包含特定值的所有列表元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)while 'cat' in pets:pets.remove('cat')print(pets)#使用用户输入来天聪字典
responses = {}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:#提示用户输入被调查者的名字和回答name = input("\nWhat is your name?")response =input("which mountain would you like to climb someday?")#将答卷存储在字典中responses[name] = response#看看是否还有人要参与调查repeat = input("woulid you like to let another person respond?(yes/no)")if repeat == 'no' or repeat == "NO":polling_active = False#调查结果,显示结果
print("\n----poll results ----")
for name ,response in responses.items():print(name +" would like to climb "+response+".")
运行结果:
If you tell us ho you are ,we can personalize the message you see.
What is your first name?EircHello, Eirc!
Verifying user:Candace
Verifying user:Brian
Verifying user:AliceThe following users have been confirmed:
Candace
Brian
Alice
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']What is your name?Eric
which mountain would you like to climb someday?Lynn
woulid you like to let another person respond?(yes/no)no----poll results ----
Eric would like to climb Lynn.