第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."