第六章 字典
字典定义
字典遍历
增删改
嵌套:字典存储在列表、列表存储在字典、字典存储在字典
dictionary={'key1':value1,'key':'value2'}
print (dictionary['key1'])
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
print(dict1['abc'])
print(dict2[98.6])
#添加键值对
alien_0={'color':'green','points':5}
alien_0['x_position']=0
alien_0['y_position']=25
#修改字典中的值
alien_0['color']='yellow'
print("The alien is now "+alien_0['color']+".")
#对一个能够以不同速度移动的外星人的位置进行跟踪。为此,
#我们将存储该外星人的当前速度,并据此确定该外星人将向右移动多远:
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']))
#删除键—值对 永远删除
alien_0={'color':'green','points':5}
print(alien_0)
del alien_0['points']
print(alien_0)
#遍历 items()键值对 keys() values() 按顺序遍历
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
for key,value in dict.items():
print(key,value)
for key in dict.keys():
print(key)
for key in sorted(dict.keys()):
print(key)
#嵌套
#字典存储在列表中
aliens=[]
for alien_number in range(0,30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color']=='green':
alien['color']='yellow'
alien['speed']='medium'
alien['points']=10
elif alien['color']=='yellow':
alien['color']='red'
alien['speed']='fast'
alien['points']=15
for alien in aliens[0:5]:
print(alien)
print("...")
#列表存储在字典中
#存储所点披萨的信息
pizza={'crust':'thick','toppings':['mushrooms','extra c heese']}
print("You ordered a "+pizza['crust']+"-crust pizza"+"with the following toppings:")
for topping in pizza['toppings']:
print("\t"+topping)
#字典中存储字典
users={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princerton',
},
'mcuric': {
'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())