一、一个简单的字典:alien_0存储外星人的颜色和点数,使用print打印出来
alien_0 = {‘color‘: ‘green‘,‘points‘: 5}
print(alien_0[‘color‘])
print(alien_0[‘points‘])
#输出结果:
green
5
二、使用字典:键-值,值可以为数字、字符串、列表或字典。字典用{ }标识。
1. 访问字典中的值
alien_0 = {‘color‘: ‘green‘,‘points‘: 5}
new_points = alien_0[‘points‘]
print("You just earned " + str(new_points) + ‘ points!‘)
#输出结果:You just earned 5 points!
解析以上代码
a. 先定义一个字典
b. 将points这个键对应的值存储到new_points中
c. 将整数转换成字符串,输出玩家获得了多少点
2. 添加键-值对:字典是一种动态结构,可随时在其中添加键-值对。python不关注键-值对添加的顺序,只关心键-值之间的关联关系。
alien_0 = {‘color‘: ‘green‘,‘points‘: 5}
print(alien_0)
alien_0[‘x_position‘]=0
alien_0[‘y_position‘]=25
print(alien_0)
#输出结果:
{‘color‘: ‘green‘, ‘points‘: 5}
{‘color‘: ‘green‘, ‘points‘: 5, ‘x_position‘: 0, ‘y_position‘: 25}
3. 先创建一个空字典
alien_0 = {}
alien_0[‘color‘] = ‘green‘
alien_0[‘points‘] = 5
print(alien_0)
#输出结果:{‘color‘: ‘green‘, ‘points‘: 5}
备注:使用字典来存储用户提供的数据或在编写能自动生成大量键-值对的代码时,通常需要定义一个空字典。
4. 修改字典中的值:对一个能够以不同速度移动的外星人的位置进行跟踪,确定外星人将向右移动多远
alien_0 = {‘x_position‘:0,‘y_position‘:25,‘speed‘:‘medium‘}
print("original x_position:" + 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‘]))
#输出结果:
original x_position:0
New x_position:2
解析以上代码:
a. 定义一个外星人,包含初始的x 坐标和y 坐标,速度 ‘medium’,并打印出原始的x 坐标
b. 使用if-elif-else 结构来确定外形人向右移动多远,并将这个值存储在变量x_increment中
c. 确定移动量后,将x_increment 和x_position 当前的值相加,再将结果关联到字典的键x_position 中,并打印出x_position
5. 删除键-值对:对于字典中不需要的信息,可用del 语句将对应的键-值对彻底删除。
alien_0 = {‘color‘:‘green‘,‘points‘:5}
print(alien_0)
del alien_0[‘points‘]
print(alien_0)
#输出结果:
{‘color‘: ‘green‘, ‘points‘: 5}
{‘color‘: ‘green‘}
6. 由类似对象组成的字典:字典多行显示
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
print("Sarah‘s favorite language is " +
favorite_language[‘sarah‘].title() +
".")
#输出结果:
Sarah‘s favorite language is C.
三、遍历字典
1. 遍历所有的键-值对
user_0 = {
‘username‘:‘efermi‘,
‘first‘:‘enrico‘,
‘last‘:‘fermi‘
}
for key,value in user_0.items():
print("\nKey:"+ key)
print("Value:"+value)
#输出结果:
Key:username
Value:efermi
Key:first
Value:enrico
Key:last
Value:fermi
解析以上代码:
a. 遍历字典的for 循环,可声明两个变量,用于存储键-值对中的键和值; items() 函数以列表返回可遍历的(键, 值) 元组数组。
b. 使用两个变量来打印每个键及其关联的值;\n:确保在输出每个键-值对前插入一个空行
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() + ".")
#输出结果:
Jen‘s favorite language is Python.
Sarah‘s favorite language is C.
Edward‘s favorite language is Ruby.
Phil‘s favorite language is Python.
2. 遍历字典中的所有键:方法keys( )
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
for name in favorite_language.keys(): #提取字典favorite_language中的所有键,并依次存储到变量name中
print(name.title()) #输出列出每个被调查的名字
#输出结果:
Jen
Sarah
Edward
Phil
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
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()+"!"
)
# 输出结果:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!
解析以上代码
a. for循环遍历所有的key
b. 再用if 判断name变量是否在friends 列表中,如果在,就在key后面再打印一句话来表示其朋友喜欢的语言
3. 按顺序遍历字典中的所有值:for循环对返回的键进行排序。可用函数 sorted( )来获得按特定顺序排序的键列表的副本。
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
for name in sorted(favorite_language.keys()): #对方法dictionary.keys( )的结果调用了函数sorted( ),让python列出字典中所有的键,并在遍历前对这个列表进行排序。
print(name.title()+ ",thank you for taking the poll.")
#输出结果:
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 poll.
4. 遍历字典中的所有值:使用方法values( ),它返回一个值列表,而不包含任何键。
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
print("The following language have been mentioned:")
for language in favorite_language.values(): #这条for语句提取字典中的每个值,并将它们依次存储到变量language中。通过打印这些纸,就获得一个列表。
print(language.title()) # dictionary.values( )的缺点:不考虑值得重复性,无法剔除重复项
#输出结果:
The following language have been mentioned:
Python
C
Ruby
Python
备注:为了剔除元素中的重复项,使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的。
favorite_language = {
‘jen‘: ‘python‘,
‘sarah‘:‘c‘,
‘edward‘:‘ruby‘,
‘phil‘:‘python‘,
}
print("The following language have been mentioned:")
for language in set(favorite_language.values()): #集合(set)找到列表中独一无二的元素,并使用这些元素来创建一个集合
print(language.title())
#输出结果:
The following language have been mentioned:
C
Python
Ruby
四、嵌套
需要将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套。列表中嵌套字典,或者字典中嵌套列表或字典。
1. 字典列表
A. 需要创建多个外形人的信息。方法:创建一个外星人的列表,其中每个外星人都是一个字典,包含有关该外星人的各种信息。
#创建一个用于存储外星人的空列表
aliens =[]
#创建30个绿色的外星人
for alien_number in range(30):
new_alien = {‘color‘:‘green‘,‘point‘:5,‘speed‘:‘slow‘}
aliens.append(new_alien)
#显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("...")
#显示创建了多少个外星人
print("Total number of aliens:" + str(len(aliens)))
#输出结果:
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
...
Total number of aliens:30
解析以上代码:
a. 创建一个空列表,用来存储接下来创建的所有外星人
b. 用range方法创建30个外星人,并将其附件到列表aliens 末尾
c. 使用切片来打印前五个外星人
d. 打印列表长度
B.将前三个外星人修改为黄色的,速度为中等且值10个点;如果外星人有黄色,则改为红色速度快速且值15个点。用for循环和if-elif 语句来修改。
#创建一个用于存储外星人的空列表
aliens =[]
#创建30个绿色的外星人
for alien_number in range(0,30):
new_alien = {‘color‘:‘green‘,‘point‘:5,‘speed‘:‘slow‘}
aliens.append(new_alien)
#修改外星人字典中的value
for alien in aliens[0:3]:
if alien[‘color‘] ==‘green‘:
alien[‘color‘]= ‘yellow‘
alien[‘point‘] = 10
alien[‘speed‘] = ‘medium‘
elif alien[‘color‘]==‘yellow‘:
alien[‘color‘]= ‘red‘
alien[‘point‘] = 15
alien[‘speed‘] = ‘fast‘
#显示前五个外星人
for alien in aliens[0:5]:
print(alien)
print("...")
#输出结果:
{‘color‘: ‘yellow‘, ‘point‘: 10, ‘speed‘: ‘medium‘}
{‘color‘: ‘yellow‘, ‘point‘: 10, ‘speed‘: ‘medium‘}
{‘color‘: ‘yellow‘, ‘point‘: 10, ‘speed‘: ‘medium‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
{‘color‘: ‘green‘, ‘point‘: 5, ‘speed‘: ‘slow‘}
...
2. 字典中存储列表
A. 需要在字典中将一个键关联多个值时,需要在字典中嵌套一个列表。如披萨配料,不仅包含配料列表,也包含其他有关披萨的描述
#存储所点披萨的信息
pizza = {
‘crust‘:‘thick‘, #创建的字典,一个键‘crust’,值‘thick’;另一个键‘topping’,值是一个列表,包含顾客要求要添加的所有配料
‘toppings‘:[‘mushrooms‘,‘extra cheese‘],
}
#概述所点的披萨
print("You ordered a "+ pizza[‘crust‘] + "-crust pizza "+
"with the following toppings:")
for topping in pizza[‘toppings‘]: #for循环是问了访问配料列表,使用键‘toppings’
print("\t" + topping)
#输出结果:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
B. 在for循环中做if-判断
favorite_languages = {
‘jen‘:[‘python‘,‘ruby‘],
‘sarah‘:[‘c‘],
‘edward‘:[‘ruby‘,‘go‘],
‘phil‘:[‘python‘,‘haskell‘],
}
for name,languages in favorite_languages.items():
if len(languages) !=1: #用len(language)判断是否是多种语言,如果是,就按if模块输出,如果不是,就按else模块输出
print("\n"+ name.title() + "‘s favorite language are:")
for language in languages:
print("\t"+language.title())
else:
for language in languages:
print("\n"+ name.title() + "‘s favorite language is: " + language.title())
#输出结果:
Jen‘s favorite language are:
Python
Ruby
Sarah‘s favorite language is: C
Edward‘s favorite language are:
Ruby
Go
Phil‘s favorite language are:
Python
Haskell
3. 在字典中存储字典:多个网站用户,每个都有独特的用户名作为字典的键,用户信息用另一个字典存储作为字典的值
users = {
‘aeinstein‘:{ #用户名有两个作为键,两个用户的信息用字典表示作为值
‘first‘:‘albert‘,
‘last‘:‘einstein‘,
‘location‘:‘princeton‘,
},
‘mcurie‘:{
‘first‘:‘marie‘,
‘last‘:‘curie‘,
‘location‘:‘paris‘,
},
}
for username, user_info in users.items(): #遍历字典users,依次将每个键存储在变量username中,依次将与当前键相关联的字典存储在变量user_info中
print("\nUsername:" + username) #将用户名打印出来
full_name = user_info[‘first‘] + " " +user_info[‘last‘] #访问内部字典
location = user_info[‘location‘]
print("\tFull name: " + full_name.title()) #打印用户的简要信息
print("\tLocation: " + location.title())
#输出结果:
Username:aeinstein
Full name: Albert Einstein
Location: Princeton
Username:mcurie
Full name: Marie Curie
Location: Paris
原文:https://www.cnblogs.com/heiqiuxixi/p/12335107.html