字典的运用

6-1 人 :使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中
的每项信息都打印出来。

Name = {'first_name':'ye','last_name':'yvonne','city':'shanghai'}
print('first_name:' + Name['first_name'].title())
print('last_name:' + Name['last_name'].title())
print('city:' + Name['city'].title())
 
6-2 喜欢的数字 :使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存
储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。

favorite_numbers = {'Yvonne':5, 'Jacky':8, 'Khae':6, 'Shen':1, 'Benny':3}
for name, number in favorite_numbers.items():
print(name.title() + "'s favorite number is:" + str(number) + '.')
 

6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt' 。
使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
使用循环将该字典中每条河流的名字都打印出来。
使用循环将该字典包含的每个国家的名字都打印出来。



rivers = {'nile':'egypt','changjiang':'china','La Seine':'french'}

for river,value in rivers.items():
print(river.title() + ' runs through ' + value.title())

for river in rivers.keys():
print(river.title())

for country in rivers.values():
print(country.title())



6-6 调查 :在6.3.1节编写的程序favorite_languages.py中执行以下操作。
创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
 
favorite_languages = {'Yvonne':'english','Jacky':'french','Shen':'chinese','Benny':'russian'}

names_list = ['yvonne','shen','sofi','ben']

for name in names_list:
if name.title() in favorite_languages.keys():
print('%s'%name.title() + ',Thank you for join us.')
else:
print('%s'%name.title() + ',Welcome to join us.')

student1 = {'ye': '一班', '学号': '32号', '成绩': '优异'}
student2 = {'jia': '二班', '学号': '5号', '成绩': '中等'}
student3 = {'wang': '一班', '学号': '3号', '成绩': '优异'}
student4 = {'xiao': '三班', '学号': '12号', '成绩': '优异'}
students = [student1,student2,student3,student4]

for student in students:
print(student)

6-9 喜欢的地方 :创建一个名为favorite_places 的字典。
在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练
习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。

favorite_places = {'Yvonne':['hangzhou','xizang','xinjiang'],'Jacky':['chongqing','chengdu','xiamen'],
'Sofi':['pairs','ohio','london']}


for name,places in favorite_places.items():
print(name.title() + '最喜欢的地方是:')
for place in places:
print('\t' + place.title())


在字典中存字典

users = {'Yvonne':{'country':'china','city':'shanghai','love':'read'},
'Sofi':{'country':'england','city':'landon','love':'cook'},
'Shen':{'country':'china','city':'landon','love':'act'}}

for name,user_info in users.items():
print('\nUsername:'+ name)
print('\tCountry:' + user_info['country'].title())
print('\tCity:' + user_info['city'].title())
print('\tLove:' + user_info['love'].title())
 

posted on 2017-11-27 11:22  yvonne_ye  阅读(903)  评论(1编辑  收藏  举报

导航