6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存 储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt' 。
6-9 喜欢的地方 :创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练 习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
num_suki = {'Niki': 2, 'Betty' : 3, "Linda": 5, "Whitney": 8, 'Lily': 11} for name, num in num_suki.items(): print(name + '喜欢的数字是' + str(num))输出:
Niki喜欢的数字是2 Betty喜欢的数字是3 Linda喜欢的数字是5 Whitney喜欢的数字是8 Lily喜欢的数字是11
6-5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是'nile': 'egypt' 。
使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
使用循环将该字典中每条河流的名字都打印出来。
使用循环将该字典包含的每个国家的名字都打印出来。
使用循环将该字典中每条河流的名字都打印出来。
使用循环将该字典包含的每个国家的名字都打印出来。
rivers = dict(zip(["Nile", "Amazon", "yangtzeRiver"], ["Egypt", "Brazil", "China"])) for river, country in rivers.items(): print('The ' + river + ' runs through ' + country + '.') for river in rivers.keys(): print(river) for country in rivers.values(): print(country)输出:
The Nile runs through Egypt. The Amazon runs through Brazil. The yangtzeRiver runs through China. Nile Amazon yangtzeRiver Egypt Brazil China
6-9 喜欢的地方 :创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练 习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
places_suki = dict.fromkeys(['Lily', 'Lucy', 'Tom']) places_suki['Lily'] = ['广州塔', '越秀山', '上下九'] places_suki['Lucy'] = ['海珠桥', '花城广场'] places_suki['Tom'] = ['长隆动物园'] for name, l in places_suki.items(): print(name + '喜欢:', end = '') for places in l: print(places, end = ' ') print()输出:
Lily喜欢:广州塔 越秀山 上下九 Lucy喜欢:海珠桥 花城广场 Tom喜欢:长隆动物园6-11 城市:创建一个名为cities的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = dict.fromkeys(['HongKong', 'Singapore', 'Tokyo']) properties = ['country', 'population', 'fact'] cities['HongKong'] = dict(zip(properties, ['中国香港', '730万', '港独'])) cities['Singapore'] = dict(zip(properties, ['星加坡', '530万', '李家坡'])) cities['Tokyo'] = dict(zip(properties, ['岛国', '3670万', 'hot'])) for city, pro in cities.items(): print(city) print(properties[0] + ':' + pro['country']) print(properties[1] + ':' + pro['population']) print(properties[2] + ':' + pro['fact'])输出:
HongKong country:中国香港 population:730万 fact:港独 Singapore country:星加坡 population:530万 fact:李家坡 Tokyo country:岛国 population:3670万 fact:hot