6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_num = {'alice': 1, 'bob': 2, 'carol': 3, 'dog': 233, 'egg': 23333}
for key, value in favorite_num.items():
print(key.title() + "'s favorite number is " + str(value) + '.')
输出:
Carol's favorite number is 3.
Dog's favorite number is 233.
Alice's favorite number is 1.
Bob's favorite number is 2.
Egg's favorite number is 23333.
注意:Python 3.5及以前的版本不关心键-值对的存储顺序,而Python 3.6及之后的版本以定义时的顺序作为存储顺序。
6-6 调查:在6.3.1节编写的程序favorite_languages.py中执行以下操作。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".") # favorite_languages.py
people_inverstigated = ['jen', 'edward']
for person in favorite_languages:
if person in people_inverstigated:
print('Thank you, ' + person.title() + '!')
else:
print('Please participate in the survey, ' +
person.title() + '!')
输出:
Phil's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Jen's favorite language is Python.
Please participate in the survey, Phil!
Please participate in the survey, Sarah!
Thank you, Edward!
Thank you, Jen!
6-10 喜欢的数字:修改为完成练习6-2而编写的程序,让每个人都可以有多个喜欢的数字,然后将每个人的名字及其喜欢的数字打印出来。
favorite_num = {
'alice': [1, 2, 3],
'bob': [11, 12, 13],
'carol': [6, 66, 666],
'dog': [233, 555],
'egg': [23333],
}
for key, value in favorite_num.items():
print('Name: ' + key.title())
print('Favorite number: ' + str(value) + '\n')
输出:
Name: Egg
Favorite number: [23333]
Name: Dog
Favorite number: [233, 555]
Name: Alice
Favorite number: [1, 2, 3]
Name: Bob
Favorite number: [11, 12, 13]
Name: Carol
Favorite number: [6, 66, 666]