赞
踩
字典是 Python 提供的一种常用的数据结构,它用于存放具有映射关系的数据。
alien_0 = {'color':'green','points': 5}
print(alien_0['color'])
print(alien_0['points'])
green
5
比如有份成绩表数据,语文:79,数学:80,英语:92,这组数据看上去像两个列表,但这两个列表的元素之间有一定的关联关系。如果单纯使用两个列表来保存这组数据,则无法记录两组数据之间的关联关系。
为了保存具有映射关系的数据,Python 提供了字典,字典相当于保存了两组数据(键值对,Key-Value Pair),其中一组数据是关键数据,被称为 key;另一组数据可通过 key 来访问,被称为 value。形象地看,字典中 key 和 value 的关联关系如图所示:
指定字典名(alien_0)+键(color)可获得值(green)
alien_0 = {'color':'green'}
print(alien_0['color'])
green
# 外星人被射杀后打印获得的分数
alien_0 = {'color':'green','points': 5}
new_points = alien_0['points']
print(f"You just earned {new_points} points!")
You just earned 5 points!
alien_0 = {'color':'green','points': 5}
print(alien_0)
#新增外星人的x坐标和y坐标
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
注意:
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
{'color': 'green', 'points': 5}
alien_0 = {'color': 'green', 'points': 5}
print (f"The alien is {alien_0['color']}")
alien_0['color'] = 'yellow'
print (f"The alien is {alien_0['color']}")
The alien is green
The alien is yellow
任务: 对一个能够以不同速度移动的外星人进行位置跟踪。首先存储该外星人的当前速度,并据此确定该外星人将向右移动多远
alien_0 = {'x_position': 0,
'y_position': 25,
'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
Original position: 0
New position: 2
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
# 任务:打印sarah喜欢的编程语言
print(f"Sarah's favorite language is {favorite_languages['sarah'].title()}.")
Sarah's favorite language is C.
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('point', 'No point value assigned.')
print(point_value)
No point value assigned.
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('point')
print(point_value)
None.
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
注意:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name, language in favorite_languages.items():
print(f"{name.title()}' favorite language is {language.title()}.")
Jen' favorite language is Python.
Sarah' favorite language is C.
Edward' favorite language is Ruby.
Phil' favorite language is Python.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen
Sarah
Edward
Phil
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
friends = ['sarah','phil']
for name in favorite_languages.keys():
print(f"Hi, {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
Hi, Jen.
Hi, Sarah.
Sarah, I see you love C!
Hi, Edward.
Hi, Phil.
Phil, I see you love Python!
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
print("The following language have been mentioned:")
for language in favorite_languages.values():
print(language.title())
Python
C
Ruby
Python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
print("The following language have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
The following language have been mentioned:
Python
C
Ruby
集合和字典:
任务: 如何管理多个外星人
alien_0 = {'color':'green','points': 5}
alien_1 = {'color':'yellow','points': 10}
alien_2 = {'color':'red','points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
任务: 如何创建多个外星人
#创建一个用于存储外星人的空列表 aliens = [] #创建30个外星人 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) #显示前5个外星人 for alien in aliens[:5]: print(alien) print("...") # 显示创建了多少外星人 print(f"Total number of aliens: {len(aliens)}")
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
任务: 修改前3个外星人的颜色,得分和速度
#创建一个用于存储外星人的空列表 aliens = [] #创建30个外星人 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yallow' alien['speed'] = 'medium' alien['points'] = 10 #显示前5个外星人 for alien in aliens[:5]: print(alien)
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
任务: 存储顾客所点的披萨的信息
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
#概述所点的披萨
print(f"You order a {pizza['crust']}-crust pizza with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
You order a thick-crust pizza with the following toppings:
mushrooms
extra cheese
任务: 存储多个用户信息
users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton' }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris' }, } for username, user_info in users.items(): print(f"\nUsername: {username}") full_name = f"{user_info['first']} {user_info['last']}" location = user_info['location'] print(f"\tFull name: {full_name.title()}") print(f"\tLocation: {location.title()}")
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。