python-字典的学习

'''在Python中,字典字 是一系列键—值对值 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。
与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
在Python中,字典用放在花括号{}中的一系列键—值对表示
'''
customer={'name':"claire",'age':18,'height':160,'weight':45}
# print(customer)
# print(customer['name'])
# customer['hire_year']=2016 #增加一个键值对
# print(customer)
# customer['name']="yeh" #修改name的值
# print(customer)
# del customer['weight']
# print(customer) #删除'weight'
'''
遍历字典
遍历所有的键 遍 —值对值
'''
# for key,value in customer.items():
#     print("\nKey:"+key)
#     print("Value:"+str(value))
'''
6-6 调查调 :在6.3.1节编写的程序favorite_languages.py中执行以下操作。
创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
'''
# favorite_languages={'claire':'linux','ruby':'C','Guni':'python','Glen':'C++'}
# print(favorite_languages)
# names=['Dandan','claire','Xinmin','yulan','Glen']
# for name in names:
#     if name in favorite_languages.keys():
#         print(str(name)+" is included,thank you!")
#     else:
#         print(str(name)+" is not included , please invite him")
''' 6-7:在为完成练习6-1而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为people 的列表中。遍历这个列表,将其中每个人的所有
# 信息都打印出来。'''
# Cliare={"first_name":"fu","last_name":"Dandan","City":"Nanjing","age":18}
# Jone={"first_name":"Lu","last_name":"Mingyu","City":"Nanjing","age":20}
# Lynn={"first_name":"Li","last_name":"Linli","City":"Shanghai","age":18}
# people=[Cliare,Jone,Lynn]
# for person  in people:
#     print(person)
# 6-8 创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
'''6-9 创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练
# 习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。'''
# favorite_places={"claire":"Suzhou","Mingyu":["hangzhou","suzhou","chengdu"],"Linli":"shanghai"}
# print(favorite_places)
# for name,cities in favorite_places.items():
#     if name=="Mingyu":
#         for city in favorite_places["Mingyu"]:
#             print(str(name) + " favourite cite is " + str(city))
#     else:
#         print(str(name) + " favourite cite is " + str(cities))
# 6-10 修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
# 6-11 创建一个名为cities的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该
# 城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities={'nanjing':{"country":"China","population":"954.7w"},
"shanghai":{"country":"China","population":"2487.4w",},
"chengdu":{"country":"China","population":"2140.3w",}}
#print(cities)
for city,city_info in cities.items():
    print(str(city)+" is in "+city_info["country"]+" and there are"+city_info['population']+" in this city")
'''
nanjing is in China and there are954.7w in this city
shanghai is in China and there are2487.4w in this city
chengdu is in China and there are2140.3w in this city
'''

 

posted @ 2024-04-12 16:10  正霜霜儿  阅读(10)  评论(0编辑  收藏  举报