Python编程:从入门到实践(埃里克·马瑟斯)第六章部分习题

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

people_1 = {
    'first_name': 'zhang',
    'last_name': 'san',
    'age': 18,
    'city': 'guangzhou',
}
print(f"people_1's name is {people_1['first_name']} {people_1['last_name']},")
print(f"people_1's age is {people_1['age']},")
print(f"he lives in {people_1['city']}.")
people_1['last_name'] = 'xiao ming'
print(f"people_1's name is {people_1['first_name']} {people_1['last_name']},")

练习 6-7:人们 在为完成练习 6-1 而编写的程序中,再创建两个表示人的字典, 然后将这三个字典都存储在一个名为 people 的列表中。遍历这个列表,将其中每个人 的所有信息都打印出来。

people1 = {'first_name': 'zhang', 'last_name': 'san', 'age': 18, 'city': 'beijing'}
people2 = {'first_name': 'wang', 'last_name': 'er', 'age': 19, 'city': 'shanghai'}
people3 = {'first_name': 'li', 'last_name': 'si', 'age': 20, 'city': 'shenzhen'}
people = [people1, people2, people3]
for pp in people:
    for key, value in pp.items():
        print(key + ":" + str(value))
    print()

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

x = ['beijing', 'chengdu', 'hangzhou']
y = ['shanghai', 'wuhan']
z = ['guangzhou', 'shenzhen']
favorite_places = {'p1': x, 'p2': y, 'p3': z}
for fpk, fpv in favorite_places.items():
    print(fpk + "'s favorite places:")
    for v in fpv:
        print(v)
    print()

练习 6-11:城市 创建一个名为 cities 的字典,将三个城市名用作键。对于每座 城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城 市的事实。在表示每座城市的字典中,应包含 country、population 和 fact 等键。将每座城市的名字以及有关信息都打印出来。

cities = {
    'city1': {
        'city_name': 'c1',
        'population': '100w',
        'fact': 'f1'
    },
    'city2': {
        'city_name': 'c2',
        'population': '80w',
        'fact': 'f2'
    },
    'city3': {
        'city_name': 'c3',
        'population': '90w',
        'fact': 'f3'
    },
}

for city_i, city_info in cities.items():
    print(f"{city_i.title()} is {city_info['city_name'].title()},")
    print(f"the population is {city_info['population']}, and the fact of the city is  {city_info['fact']}")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值