6-1 人 : 使用一个字典来存储一个熟人的信息, 包括名、 姓、 年龄和居住的城市。 该字典应包含键first_name 、 last_name 、 age 和city 。 将存储在该字典中的每项信息都打印出来。
dict = {}
dict['first_name'] = 'David'
dict['last_name'] = 'Chan'
dict['age'] = 20
dict['city'] = 'Guangzhou'
print(dict)
结果:
{'first_name': 'David', 'last_name': 'Chan', 'age': 20, 'city': 'Guangzhou'}
6-2 喜欢的数字 : 使用一个字典来存储一些人喜欢的数字。 请想出5个人的名字, 并将这些名字用作字典中的键; 想出每个人喜欢的一个数字, 并将这些数字作为值存储在字典中。 打印每个人的名字和喜欢的数字。 为让这个程序更有趣, 通过询问朋友确保数据是真实的。
fav_num = {
'David': 9,
'Jackson': 666,
'Toffc': 7,
'Alice': 3,
'Jessica': 1,
}
for key, value in fav_num.items():
print(key + "'s favorite num is " + str(value) + '.')
结果:
David's favorite num is 9.
Jackson's favorite num is 666.
Toffc's favorite num is 7.
Alice's favorite num is 3.
Jessica's favorite num is 1.
6-3 词汇表 : Python 字典可用于模拟现实生活中的字典, 但为避免混淆, 我们将后者称为词汇表。
想出你在前面学过的 5 个编程词汇, 将它们用作词汇表中的键, 并将它们的含义作为值存储在词汇表中。
以整洁的方式打印每个词汇及其含义。
为此, 你可以先打印词汇, 在它后面加上一个冒号, 再打印词汇的含义; 也可在一行打印词汇, 再使用换行符(\n ) 插入一个空行, 然后在下一行以缩进的方式打印词汇的含义。
voc = {
'print': 'Display information in one line.',
'if': 'Run the language in the following indentation if the condition matches.',
'for': 'Traverse the element in the list or tuple, etc.',
'while': 'Loop until the condition matches.',
'range': 'Create an integer list object.',
}
print("print: " + voc['print'])
print("if: " + voc['if'])
print("for: " + voc['for'])
print("while: " + voc['while'])
print("range: " + voc['range'])
结果:
print