python第五次练习

例题6-5

  描述:创建字典,存储三条大河流及其流经国家。
             打印指定消息,分别打印全部河流和国家。
  代码:

river_country = {
    'yellow river': 'china',
    'nile': 'egypt',
    'amazon river': 'brazil',
    }
for river,country in river_country.items():
    print('The ' + river.title() + 
        ' runs through ' + 
        country.title() +
        '.')
print('Rivers:')
for river in river_country.keys():
    print(river.title())
print('\nCountries:')
for country in river_country.values():
    print(country.title())

  结果:
这里写图片描述

例题6-9 喜欢的地方

  描述:创建favorite_places字典,将三个人的名字用作键;
             对于其中的每个人,都存储他喜欢的1~3个地方。
             把名字和地方打印。
  扩展:创建后在字典中添加一个人,打印字典和长度,再删除,重复。
  代码:

favorite_places = {
    'Eric': ['Japan', 'Africa', 'China'], 
    'Ponyo': ['Australia', 'Finland', 'Japan'], 
    'Reading': ['Singapore', 'Japan', 'China'],
    }
favorite_places['Mary'] = ['England', 'America', 'Korea']
for people in favorite_places.keys():
    print('\nName: ' + people)
    print('Places: ')
    for place in favorite_places[people]:
        print(place)
print(len(favorite_places))
del favorite_places['Mary']
print(len(favorite_places))
for people in favorite_places.keys():
    print('\nName: ' + people)
    print('Places: ')
    for place in favorite_places[people]:
        print(place)

  结果:
这里写图片描述

例题6-11

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

cities = {
    'Guangzhou': {
        'Country': 'China',
        'Population': '14.4984million',
        'Fact': 'Many delicious foods here.',
        },
    'Seoul': {
        'Country': 'Korea',
        'Population': '10.14 million',
        'Fact': 'Cosmetics shopping paradise.',     
        },
    'Brisbane': {
        'Country': 'Australia',
        'Population': '2.27million',
        'Fact': 'Fantastic weather.',       
        },      
    }
for city in cities.keys():
    print('\n' + city + ':')
    for key,value in cities[city].items():
        print(key + ': ', end='')
        print(value)

  结果:
这里写图片描述

发现的问题:

  1. 对于key,value不要忘记items keys values
  2. 字典的值为字典时要注意,创建时不要忘记逗号(在一项结束后)。
  3. python一行的字数有限制 要注意换行和缩进的规范(字典,print),不要忘记逗号(最好在字典的最后一项也加上逗号)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值