Python编程:从入门到实践——练习题答案(第六章)

第6章 字典

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

person = {
   
    'first_name': 'Iverson',
    'last_name': 'Allen',
    'age': 32,
    'city': 'NYC',
    }

print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])

运行结果:

Iverson
Allen
32
NYC

6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。

favorite_numbers = {
   
    'xiaoming': 21,
    'xiaohong': 1,
    'xiaofang': 6,
    'xianoli': 18,
    'xiaowang': 3,
    }

num = favorite_numbers['xiaoming']
print("xiaoming's favorite number is " + str(num) + ".")

num = favorite_numbers['xiaohong']
print("xiaohong's favorite number is " + str(num) + ".")

num = favorite_numbers['xiaofang']
print("xiaofang's favorite number is " + str(num) + ".")

num = favorite_numbers['xianoli']
print("xianoli's favorite number is " + str(num) + ".")

num = favorite_numbers['xiaowang']
print("xiaowang's favorite number is " + str(num) + ".")

运行结果:

xiaoming's favorite number is 21.
xiaohong's favorite number is 1.
xiaofang's favorite number is 6.
xianoli's favorite number is 18.
xiaowang's favorite number is 3.

6-3 词汇表: Python 字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。

#想出你在前面学过的 5 个编程词汇,将它们用作词汇表中的键,
#并将它们的含义作为值存储在词汇表中。

glossary = {
   
    'string': 'A series of characters.',
    'comment': 'A note in a program that the Python interpreter ignores.',
    'list': 'A collection of items in a particular order.',
    'loop': 'Work through a collection of items, one at a time.',
    'dictionary': "A collection of key-value pairs."
  • 17
    点赞
  • 79
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值