一、python字典dict:将相关信息关联起来,是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。
1.创建字典
创建一个绿色,5点的外星人
alien_0={'color':'green','point':5}
print(alien_0['color'])
print(alien_0['point'])
green
5
2.字典的使用:字典的标志符号{ },键值对于,键值之间冒号分隔,键值对(项)之间逗号隔开。 指定键时,返回对应的值,键必须唯一,值不要求,可以是任何不变的数据类型(元组,字符串,数)。 keys—values=items。字典讲究映射,不讲究顺序
#访问字典中的值,字典名【键】
alien_0={'color':'green','point':5}
print(alien_0['point'])
#外星人游戏中玩家获得的点数
alien_0={'color':'green','point':5}
new_points=alien_0['point'] #获取point对应的值 5 ,赋给新的变量new_points
print("you just earned " +str(new_points)+" points!") #new_points转化为字符输出
5
you just earned 5 points!
3.添加键值对:字典是一种动态结构,可以随时添加键值对,方法:字典名[ 键 ] = 值
#添加外星人的位置坐标
alien_0={'color':'green','point':5}
alien_0['x_position']=0#添加值
alien_0['y_position']=25#添加值
alien_0['color']='yellow'#修改值
print(alien_0)
{‘color’: ‘yellow’, ‘point’: 5, ‘x_position’: 0, ‘y_position’: 25}
#创建空字典,添加键值对
alien_1={ }
type(alien_1) #dict类型
alien_1['color']='green'
alien_1['point']=5
print(alien_1)
{‘color’: ‘green’, ‘point’: 5}
#修改字典中的值
#游戏:对一个能以不同的速度移动的外星人进行位置跟踪
alien_0={'color':'green','point':5,'x_position':0,'y_position':25,'speed':'medium'}
print('original x_position is '+str(alien_0['x_position']))
alien_0['speed']='fast'
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 is "+str(alien_0['x_position']))
original x_position is 0
new x_position is 3
5.删除键值对 del语句 永久删除
alien_0={'color':'green','point':5,'x_position':0,'y_position':25,'speed':'medium'}
del alien_0['speed']#删除speed键值对
print(alien_0)
{‘color’: ‘green’, ‘point’: 5, ‘x_position’: 0, ‘y_position’: 25}
6.遍历字典,内置函数 keys键,values值,items项
dict1={}
dict1=dict1.fromkeys(range(30),'赞')
print(dict1)
print(dict1.keys())
print(dict1.values())
print(dict1.items())
{0: ‘赞’, 1: ‘赞’, 2: ‘赞’, 3: ‘赞’, 4: ‘赞’, 5: ‘赞’, 6: ‘赞’, 7: ‘赞’, 8: ‘赞’, 9: ‘赞’, 10: ‘赞’, 11: ‘赞’, 12: ‘赞’, 13: ‘赞’, 14: ‘赞’, 15: ‘赞’, 16: ‘赞’, 17: ‘赞’, 18: ‘赞’, 19: ‘赞’, 20: ‘赞’, 21: ‘赞’, 22: ‘赞’, 23: ‘赞’, 24: ‘赞’, 25: ‘赞’, 26: ‘赞’, 27: ‘赞’, 28: ‘赞’, 29: ‘赞’}
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])
dict_values([‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’, ‘赞’])
dict_items([(0, ‘赞’), (1, ‘赞’), (2, ‘赞’), (3, ‘赞’), (4, ‘赞’), (5, ‘赞’), (6, ‘赞’), (7, ‘赞’), (8, ‘赞’), (9, ‘赞’), (10, ‘赞’), (11, ‘赞’), (12, ‘赞’), (13, ‘赞’), (14, ‘赞’), (15, ‘赞’), (16, ‘赞’), (17, ‘赞’), (18, ‘赞’), (19, ‘赞’), (20, ‘赞’), (21, ‘赞’), (22, ‘赞’), (23, ‘赞’), (24, ‘赞’), (25, ‘赞’), (26, ‘赞’), (27, ‘赞’), (28, ‘赞’), (29, ‘赞’)])
#遍历所有键值对
user_0={
'usename':'mary',
'first':'enrico',
'last':'fermi',
}
print(user_0.items())
for key,value in user_0.items():
print("\nkey:"+key)
print("value:"+value)
dict_items([(‘usename’, ‘mary’), (‘first’, ‘enrico’), (‘last’, ‘fermi’)])
key:usename
value:mary
key:first
value:enrico
key:last
value:fermi
#遍历所有的键内置函数 字典名.keys()
favorite_languages={
"mary":"C",
"sarah":"python",
"jack":"java",
}
for name in favorite_languages.keys():
print(name)
for name in favorite_languages:#python默认遍历键
print(name.title())
#遍历所有的值内置函数 字典名.values()
for language in favorite_languages.values():
print(language.title())
for name in sorted(favorite_languages.keys()):#按顺序打印 函数sorted
print(name)
mary
sarah
jack
Mary
Sarah
Jack
C
Python
Java
jack
mary
sarah
集合函数set(),类似于列表,但每个元素独一无二
favorite_languages={
"mary":"C",
"sarah":"python",
"jack":"java",
"alice":"C",
"jack":"java",
}
for name in set(favorite_languages.keys()):
print(name)
alice
jack
mary
sarah
7.嵌套:字典列表,在字典中存储列表,在字典中存储字典
#字典列表
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)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
#创建一个用来存储多个外星人的空列表,注意是列表,不是集合
aliens=[]
#创建30个外星人
for alien_number in range(30):
new_alien={"color":"green","points":5,"speed":"low"}
aliens.append(new_alien)# 此处是列表才可以用函数append,集合不可以用
#修改前三个外星人的颜色
for alien in aliens[:3]:
if alien['color']=='green': 测试条件用 = = 而不是 =
alien['color']='yellow'
alien['speed']='fast'
alien['point']='15'
#用切片方式复制前五个外星人
for alien in aliens[:5]:
print(alien)
print("...")
print("total number of aliens is "+str(len(aliens)))
{‘color’: ‘yellow’, ‘points’: 5, ‘speed’: ‘fast’, ‘point’: ‘15’}
{‘color’: ‘yellow’, ‘points’: 5, ‘speed’: ‘fast’, ‘point’: ‘15’}
{‘color’: ‘yellow’, ‘points’: 5, ‘speed’: ‘fast’, ‘point’: ‘15’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘low’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘low’}
…
total number of aliens is 30
#在字典中存储列表
#存储pizza的信息
pizza={
'crust':'thick',
'toppings':['mushroom','extra cheesw'], #字典pizza中存储列表
}
#概述所点的pizza
print("you orderd a "+pizza['crust']+"-crust pizza "+"with the follow toppings:")
for topping in pizza['toppings']:
print('\t'+topping)
you orderd a thick-crust pizza with the follow toppings:
mushroom
extra cheesw
#定义一个字典,里面的值有列表
favorite_languages={
'mary':['C','Java'],
'zhang':['C','C++','python'],
'chen':'C#',
}
#遍历字典
for name,languages in favorite_languages.items():
print("\n"+name.title()+" 's favorite language are : ")
for language in languages:
print(language)
Mary 's favorite language are :
C
Java
Zhang 's favorite language are :
C
C++
python
Chen 's favorite language are :
C
#在字典中存储字典
#创建两个用户字典,每个用户的具体信息也用字典来存储
users={
'mary':{'first name':'smith','age':18},
'xiaoxiao':{'first name':'zhang','age':22},
}
for name,informations in users.items(): #遍历users 将键存在name中,值存在informations中
print('\n'+name.title()+" 's informations are :")#打印键
print("first name is "+informations['first name'])# 打印值,按字典访问的格式
print("age is "+str(informations['age']))
#以下是错误做法
for name,informations in users.items(): #遍历users 将键存在name中,值存在informations中
print('\n'+name.title()+" 's informations are :")#打印键
for first,age in informations.items():#本处不需要使用循环
print("first name is "+informations['first name'])
print("age is "+str(informations['age']))
Mary 's informations are :
first name is smith
age is 18
Xiaoxiao 's informations are :
first name is zhang
age is 22
Mary 's informations are :
first name is smith
age is 18
first name is smith
age is 18
Xiaoxiao 's informations are :
first name is zhang
age is 22
first name is zhang
age is 22
8.总结:学会了如何定义字典,大括号{ },以及如何使用字典中的信息,字典名[键]=值,如何访问和修改字典中的值,以及如何遍历所有信息,字典名.items() 如何在列表中嵌套字典,如何在字典中嵌套列表,如何在字典中嵌套字典。