1.字典基本形式
peter_list={'height':'178','weight':'140'}#字典的基本构成
print(peter_list['height'])
print(peter_list['weight'])
字典主要由两部分构成:key:value,其中value可以是数字,字符串,列表,字典。
2.字典操作:
2.1 访问字典中的值
要获取与key相对应的value。可依次指定字典名和key。例如:
peter_list={'height':'178','weight':'140'}
print(peter_list['height'])
print(peter_list['weight'])
输出结果
178
140
2.2 添加键-值对
字典是一种动态结构,可随时在其中添加key—value对。要添加key—value对。可以依次指定字典名、用方括号将key—value对来添加元素。例如:
peter_list={'height':'178','weight':'140'}
peter_list['IQ']=100
peter_list['EQ']=50
print(peter_list)
输出结果 :
{'height': '178', 'weight': '140', 'IQ': 100, 'EQ': 50}
2.3 创建空字典
peter_list={}
peter_list['height']=178
peter_list['weight']=140
peter_list['IQ']=100
peter_list['EQ']=50
print(peter_list)
{'height': 178, 'weight': 140, 'IQ': 100, 'EQ': 50}
2.4 修改字典中的值
peter_list={'height':'178','weight':'140','IQ':'100','EQ':'50'}
peter_list['weight']='150'
peter_list['EQ']='80'
print(peter_list)
{'height': '178', 'weight': '150', 'IQ': '100', 'EQ': '80'}
2.5 删除键-对值
peter_list={'height':'178','weight':'140','IQ':'100','EQ':'50'}
del peter_list['weight']
print(peter_list)
{'height': '178', 'IQ': '100', 'EQ': '50'}
2.6 由类似对象组成的字典
grade_list={
'peter':'100',
'jack' :'99',
'tom' :'98',
'twob' :'60',
}
print('In test,recently, of the python programming. Peter get '+grade_list['peter']+' scores.')
输出结果:
In test,recently, of the python programming. Peter get 100 scores.
3.遍历字典
3.1 遍历所有的键对值
peter_list={'height':'178','weight':'150','IQ':'100'}
for key,value in peter_list.items():
print("\nKey: "+key)
print("Value: "+value)
程序第一次输入犯的错误:
1,定义字典数据类型的时候,应该使用“{}”,而不是“[]”
2,for key,value in peter_list.items():当中key和value当中的‘,’
3,同时不要忘记了,items后面的“s”
输出结果:
Key: height
Value: 178
Key: weight
Value: 150
Key: IQ
Value: 100
3.2 遍历字典中所有的键
peter_list={'height':'178','weight':'150','IQ':'100'}
for key in peter_list.keys():
if key=='IQ':
print("\nKey: "+key.upper())
else:
print("\nKey: "+key.title())
程序第一次输入犯的错误:
1,不要忘记了if-else语句在python中的强制缩进
2,if key=='IQ': 在判断字符串相等的时候,IQ的单引号不能漏掉,不然就会报类型不匹配的错误
Key: Height
Key: Weight
Key: IQ
3.3 按顺序遍历字典中的所有键-值对
name_list={'peter':'100','jack':'99','tom':'98','mary':'95','alice':'90','william':'60',}
for key,value in sorted(name_list.items()):
if value=='100':
print(key.title()+',Amazing grade.')
elif value >= '90':
print(key.title()+',Great grade.')
else:
print(key.title()+',You need to work harder.')
Alice,Great grade.
Jack,Great grade.
Mary,Great grade.
Peter,Amazing grade.
Tom,Great grade.
William,You need to work harder.
3.4 遍历字典中的所有值
name_list={'peter':'100','jack':'99','tom':'98','mary':'95','alice':'90','william':'60',}
amazing=0
great=0
ok=0
for value in sorted(name_list.values()):
if value=='100':
amazing=amazing+1
elif value >= '90':
great=great+1
else:
ok=ok+1
print("Amazing level:"+str(amazing))
print("\nGreat level:"+str(great))
print("\nOK level:"+str(ok))
需要注意的地方在于,在print时,需要将int型的amazing,great,ok转化为str类型,这样才能用+号连接,并print。
Amazing level:1
Great level:4
OK level:1
4.嵌套
4.1 字典列表
peter_list={'height':'178','weight':'150'}
alice_list={'height':'160','weight':'100'}
tom_list={'height':'170','weight':'120'}
name_list=[peter_list,alice_list,tom_list]
for name in name_list:
print(name)
{'height': '178', 'weight': '150'}
{'height': '160', 'weight': '100'}
{'height': '170', 'weight': '120'}
拓展版:(借用书中的生成外星人的例子)
aliens=[]
for alien_number in range(30):
new_alien={'color':'green','point':'5','speed':'low'}
aliens.append(new_alien)
for alien in aliens[0:5]:
print(alien)
print('...')
print('Total number of alien:'+str(len(aliens)))
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
...
Total number of alien:30
4.2 字典中储存列表
pizza={
'crust':'thick',
'toppings':['mushroom','extra cheese']
}
print("you ordered a "+pizza['crust']+"-crust pizza"+
" with the following toppings")
for topping in pizza['toppings']:
print("\t"+topping)
要注意的点在—调用pizza[ ]时,内部的‘ ’不能省去。
pizza['crust']√ pizza[crust]
ordered a thick-crust pizza with the following toppings
mushroom
extra cheese
拓展版:
skill_languages={
'peter':['C','python,','matlab'],
'rinbow':['C','java','matlab','go'],
'jam':['C','C++','matlab'],
}
for name,languages in skill_languages.items():
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())
Peter's favorite languages are:
C
Python,
Matlab
Rinbow's favorite languages are:
C
Java
Matlab
Go
Jam's favorite languages are:
C
C++
Matlab
4.3 在字典中存储字典
lists={
'jams':{
'first':'Cavaliers',
'then':'Miami Heat to Cavaliers',
'effect team':'Los Angeles Lakers',
},
'kobe':{
'first':'Los Angeles Lakers',
'then':'Los Angeles Lakers',
'effect team':'none',
}
}
for name,team in lists.items():
print("\nname:"+name)
playteam=team['first']+"-→-"+team['then']+"-→-"+team['effect team']
print("\tplayteam:"+playteam.title())
name:jams
playteam:Cavaliers-→-Miami Heat To Cavaliers-→-Los Angeles Lakers
name:kobe
playteam:Los Angeles Lakers-→-Los Angeles Lakers-→-None