6.1一个简单的字典
alien_0={'color':'green','points':'20'}
print(alien_0['color'])
注意是大括号喔,属性和值都是单引号括起来。
6.2使用字典
1.使用键值
名称[‘键’]
alien_0[‘point’]
2.添加键值
alien_0={'color':'green','points':'20'}
print(alien_0['color'])
alien_0['x_position']=0
alien_0['y_position']=20
print(alien_0)
运行结果
3.修改键值
alien_0[‘color’]=‘green’
4.删除键值对
del alien_0[‘points’]
5.由类似对象组成的字典
favorite_foods={
'Even':'cherry',
'Isak':'apple',
'Noora':'noodles',
}
print("Isak's favorite food is "+favorite_foods['Isak'].title()+" .")
运行结果:
练习
6-1 人 :使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中 的每项信息都打印出来。
person={
'first_name':'Ian',
'last_name':'Gallager',
'age':'20',
'city':'SouthSide',
}
print(person['first_name']+' '+person['last_name']+' is '+person['age']+' years old , and he lives in '+person['city'])
运行结果:
// Ian Gallager is 20 years old , and he lives in SouthSide
6.3遍历字典
1.遍历所有键值
person={
'first_name':'Ian',
'last_name':'Gallager',
'age':'20',
'city':'SouthSide',
}
print(person['first_name']+' '+person['last_name']+' is '+person['age']+' years old , and he lives in '+person['city'])
for key,value in person.items():
print("\nKey:"+key)
print("Value:"+value)
运行结果:
items()函数 : 返回的是 键_值对列表
food={
'Even':'apple',
'Eva':'carrot',
}
for name,food in food.items():
print('\nname: '+name)
print('food: '+food)
运行结果:
name: Even
food: apple
name: Eva
food: carrot
2.遍历字典中所有键
在不需要值的时候,使用函数keys()
food={
'Even':'apple',
'Eva':'carrot',
'Isak':'rice',
}
for name in food.keys():
print(name.title())
运行结果:
Even
Eva
Isak
food={
'Even':'apple',
'Eva':'carrot',
'Isak':'rice',
}
friends=['Isak','Even']
for name in food.keys():
if name in friends:
print('hi, '+name+', i see you like '+food[name].title())
运行结果:
hi Eva,i know you like carrot
hi Isak,i know you like rice
3.按照顺序遍历所有的键
上一段代码中 for循环改为
for name in sorted(food.keys())
4.遍历字典中所有的值
使用函数 values()
set()函数,删除重复的值
foods={
'Even':'apple',
'Abily':'watermenlon',
'Eva':'carrot',
'Isak':'rice',
'Ian':'cookie',
'Fiona':'rice'
}
for food in set(foods.values()):
print(food.title())
运行结果:
练习
1.河流 :创建一个字典,在其中存储三条大河流及其流经的国家。
其中一个键—值对可能是’nile’: ‘egypt’ 。
使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
rivers={
'ChangJiang':'China',
'nile':'eqypt',
'huanghe':'china',
}
for river,country in rivers.items():
print('The '+river+' runs throught '+country)
使用循环将该字典中每条河流的名字都打印出来。
for river in sorted(rivers.keys()):
print(river)
使用循环将该字典包含的每个国家的名字都打印出来。
for country in set(rivers.values()):
print(country)
2.调查 :
创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
persons=['Even','Carl','Frank','Monica','Liam','Bob']
survey_persons={
'Liam':'carrpt',
'Carl':'watermenlon',
}
for name in persons:
if name in survey_persons.keys():
print(name+", thank u for taking tests")
else:
print(name+', would u take the test?')
运行结果:
6.4嵌套
1.字典列表
简单例子:
alien_0={'color':'red','points':20}
alien_1={'color':'greem','points':30}
alien_2={'color':'yellow','points':40}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
使用range()自动生成30个外星人
aliens=[]
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 is '+str(len(aliens)))
升级版:
aliens=[]
for alien_number in range(0,30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
#改变前3个外星人
for alien in aliens[0:3]:
if alien['color']=='green':
alien['color']='red'
alien['points']=15
#显示前五个外星人
for alien in aliens[0:5]:
print(alien)
print('........')
print('Total number of aliens is '+str(len(aliens)))
运行结果:
2.在字典中存储列表
pizzas={
'crust':'thick',
'toppings':['mushroom','pepper','cheese'],
}
print('you ordered a '+pizzas['crust']+'-crust pizza'+'with the following toppings:')
for top in pizzas['toppings']:
print("\t"+top)
运行结果:
3.在字典中存储字典
定义了users字典,里面有两个键。
与每个键相关联的值 都是一个字典,其中包含用户名,年龄,地址。
users={
'Ian':{
'first':'Ian',
'last':'Milkvich',
'age':20,
'location':'home',
},
'Finoa':{
'first':'Finoa',
'last':'Gallenger',
'age':25,
'location':'cafe',
},
}
for user_name,user_info in users.items():
print('\nUsername: '+user_name)
full_name=user_info['first']+' '+user_info['last']
location=user_info['location']
print('\t Full name: '+full_name.title())
print('\t Location: '+location.title())
练习
1.宠物 :创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
cats={
'host_name':'Lin',
'feature':'lazy'
}
dogs={
'host_name':'Ian',
'feature':'cute'
}
pets=[cats,dogs]
for pet in pets:
print('\thost_name: '+pet['host_name'])
print('\tfeature: '+pet['feature'])
运行结果:
2. 喜欢的地方 :创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练 习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places={
'Ian':['Cananda','Tronto','Japan'],
'Carl':['China','India'],
'Debbie':['Amercia','Birtian'],
}
for key,values in favorite_places.items():
print(key+'would like to go to: ')
for i in values:
print('-'+i)
运行结果:
3. 城市 :创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该 城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities={
'beijing':{
'country':'China',
'population':80000,
'facts':'capital city',
},
'tokyo':{
'country':'Japan',
'population':100000,
'facts':'cherry flower blooms',
},
'NewYork':{
'country':'Amercia',
'population':90000,
'facts':'urban city',
},
}
for city,city_info in cities.items():
print(city)
country=city_info['country']
population=city_info['population']
fact=city_info['facts']
print('\tcountry: '+country)
print('\tpopulation: '+str(population))
print('\tfacts: '+fact)
运行结果