1、一个简单的字典游戏
下面是一个简单的字典,存储了有关特定外星人的信息
alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
结果:
green
5
2、使用字典
在python中字典是一系列键—值对。每个键与值相关联,可以用键来访问相关的值,与键相关的值可以是数字、字符串、列表乃至字典。事实上你可以将任何python对象用作字典中的值。
在python中,字典用放在花括号{}中的一系列键—值对表示,例子如上
3、访问字典中的值
要获取与键相关联的值,可依次指定字典名和放在方括号内的键,例子如上
4、添加键—值对
字典是一种动态结构,可随时在其中添加键—值对。
要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值
alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
#添加键—值对
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
结果
green
5
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
5、先创建一个空字典
再分行添加各个键—值对
alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
结果
{'color': 'green', 'points': 5}
6、修改字典中的值
依次指定字典名、用方括号括起的键以及与该键相关联的新值
alien_0={'color':'green'}
print('The alien is '+alien_0['color']+'.')
alien_0={'color':'yellow'}
print('The alien now is '+alien_0['color']+'.')
结果
The alien is green.
The alien now is yellow.
7、删除键—值对
alien_0={'color':'green','points':5}
del alien_0['points']
8、遍历字典
(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
(2)遍历字典中的所有键
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for name in favorite_languages.keys():
print(name.title())
结果
Jen
Sarah
Edward
Phil
(3)遍历字典中的所有值
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for language in favorite_languages.values():
print(language.title())
结果:
Python
C
Ruby
Python
9、嵌套
(1)字典列表
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}
更符合现实的情形是外星人不止三个,我们可以使用range()
#创建一个用于存储外星人的空列表
aliens=[]
#创建30个绿色的外星人
for alien_number in range(30):
new_alien={'color':'green','points':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', '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
(2)在字典中存储列表
#存储点披萨的信息
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
#概述所点的披萨
print("You ordered a "+pizza['crust']+"-crust pizza "+"with the following toppings:")
for topping in pizza['toppings']:
print("\t"+topping)
结果:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
(3)在字典中存储字典
users={
'aeinstein': {
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
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