6.1
friends_0 = {'first_name':'Hao','last_name':'zeng yao','age':22,'city':'He zhe'}
print(friends_0['first_name'])
print(friends_0['last_name'])
print(friends_0['age'])
print(friends_0['city'])
6.2
favorite_numbers = {
'Jonaka':'8',
'Jaide':'6',
'Tressa':'4',
'Paolina':'5',
'Urbana':'10',
}
number = favorite_numbers['Jonaka'].title()
print(f"Jonaka's favorite number is {number}.")
number = favorite_numbers['Jaide'].title()
print(f"Jaide's favorite number is {number}.")
number = favorite_numbers['Tressa'].title()
print(f"Tressa's favorite number is {number}.")
number = favorite_numbers['Paolina'].title()
print(f"Paolina's favorite number is {number}.")
number = favorite_numbers['Urbana'].title()
print(f"Urbana's favorite number is {number}.")
6.3
#想出你在前面学过的 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.",
}
#以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加
#上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n)
#插入一个空行,然后在下一行以缩进的方式打印词汇的含义
word = 'string'
print("\n" + word.title() + ": " + glossary[word])
word = 'comment'
print("\n" + word.title() + ": " + glossary[word])
word = 'list'
print("\n" + word.title() + ": " + glossary[word])
word = 'loop'
print("\n" + word.title() + ": " + glossary[word])
word = 'dictionary'
print("\n" + word.title() + ": " + glossary[word])
6.4
#想出你在前面学过的 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.",
'strip':'删除字符串中的空白',
'insert':'添加元素到列表中的任意位置',
'sort':'按首字母排列列表',
'reverse':'反向打印列表',
'get':'在键不存在时返回None'
}
for language,meaning in glossary.items():
print("\n"+language+":"+meaning)
6.5
rivers = {
'nile': 'egypt',
'The yellow river': 'china',
'seine': 'France',
}
for country, river in rivers.items():
print(f"The {country} runs through {river}.")
for river in rivers.keys():
print(river)
for country in rivers.values():
print(country.title())
6.6
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['sarah','phil','erin']
for name in friends:
if name in favorite_languages.keys():#易丢掉括号
print(f"{name.title()},Thank you for your cooperation.")
else:#易丢掉括号
print(f"{name.title()},Please take our survey.")
从入门到实践(第二版)第六章课后习题6.1-6.6
于 2022-10-17 20:59:01 首次发布
本文通过示例介绍了Python字典的基本操作,包括创建、访问和遍历字典元素。此外,展示了如何使用字典创建词汇表,其中包含编程术语及其解释,并以整洁格式打印。还涉及了字典与列表的结合使用,以及如何从字典中获取键、值。最后,通过示例展示了如何处理字典与列表的交互,如遍历键值对、列出所有键和值。
摘要由CSDN通过智能技术生成