Hello ~ 俗话说的好 “一日不见如隔三秋”
小道 掐指一算距第一篇“初识Python”已经过去了半个多月了,是时候该亮剑了~
这段时间着实有点忙碌a~, 工作及学习占有了我绝大部分时间,所以没来的及续上文章。
哈哈,废话说了半天该回归正题了~
DIY 2
声明:未打广告,全文知识梳理来源于《Python编程 从入门到实践(第2版)》豆瓣评分9.3
注:例中所有 >>> 符号后为输出结果
知识框图
第六章
字典
例 1 字典介绍
- 创建字典及空字典。
- 对字典 “增删改”等操作。
注:本文中的示例注释比较啰嗦,但我觉得对 0 基础的小白比较友好(虽然我也是小白,哈哈~)。虽然注释很多,但绝对没有影响代码语法,所有代码示例都可以直接复制到 IDLE 运行查看结果。有兴趣的"少侠"可以自己运行代码试试~
废话不多说直接上代码
# 例 1
# 字典
alien_0 = {'color': 'green', 'points': 5} # 创建字典
#字典放在 {} ; 键和值之间用 : 分隔;键值对之间用 , 分隔;
#字典是一系列 “键值对”。每个键与一个值相关联,用键访问相关联的值。
#值可以是数、字符串、列表乃至字典。可将任何Python对象用作字典中的值
print(alien_0['color']) # 打印 ’键‘ 关联的 ’值‘
print(alien_0['points'])
print(alien_0)
# >>> green
# >>> 5
# >>> {'color': 'green', 'points': 5}
# 添加键值对
alien_0['x_position'] = 0 # 向字典alien_0中添加,键为['x_position'],值为 0,的键值对;
alien_0['y_position'] = 25
print(alien_0) # 元素排列顺序与添加顺序相同
# >>> {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
# 创建空字典
alien_1 = {}
alien_1['color'] = 'red'
alien_1['points'] = 6
print(alien_1)
# >>> {'color': 'red', 'points': 6}
# 修改字典中的值
alien_0['speed'] = 'medium'
print(alien_0)
# >>> {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25, 'speed': 'medium'}
alien_0['speed'] = 'fast' # 可以直接重新赋值
print(alien_0)
# >>> {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25, 'speed': 'fast'}
# 拓展
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium': # 判断 键'speed' 的值为'medium'
x_increment = 2 # 变量x_increment = 2
elif alien_0['speed'] == 'fast':
x_increment = 3
alien_0['x_position'] += x_increment # 键值 = 原键值 + 新值
print(f"New x_position: {alien_0['x_position']}") # 打印更新后的键值
# >>> New x_position: 3
# 删除键值对
print(alien_0)
# >>> {'color': 'green', 'points': 5, 'x_position': 3, 'y_position': 25, 'speed': 'fast'}
del alien_0['points'] # del 语句 删除键值对
print(alien_0)
# >>> {'color': 'green', 'x_position': 3, 'y_position': 25, 'speed': 'fast'}
例 2 字典的延伸运用。
- 字典不仅可以存储一个对象的多种信息,也可以存储众多对象的同一种信息。
- 使用 get() 方法访问字典值的实例应用,通过实例可以更好了解 get() 方法的运用。
# 例 2
# 由类似对象组成的字典
favorite_languages = { # 存储众多对象的同一种信息
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
# >>> Sarah's favorite language is C.
# 使用 方法 .get() 来访问值
print(favorite_languages.get('join','NO point value assigned.'))
# 方法 .get() 第一个参数用于指定键,必不可少。
# 第二个参数为指定键不存在时返回的值,可选。未指定参数时,返回None
# >>> NO point value assigned.
例 3 遍历字典
- 方法 itmes() 配合 for循环 遍历字典的“键”和“值”
- 方法 keys() 配合 for循环 遍历字典的“键”
# 例 3
# 遍历字典
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items(): # 声明两个变量,用于存储键值对中的键和值。
# 第二部分包含字典名和方法 .itmes(),它返回一个键值对列表
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 in favorite_languages.keys(): # 方法 .keys() 可以省略,提取字典的键,赋值到变量中
print(name.title())
# >>> Jen
# >>> Sarah
# >>> Edward
# >>> Phil
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!
if 'erin' not in favorite_languages.keys(): # 核实'erin' 是否包含在这个字典中。
#方法 .keys() 并非只用于遍历,它返回一个 列表,包含字典中所有的键。
print('Erin, please take our poll!')
# >>> Erin, please take our poll!
#按特定顺序遍历字典所有键
for name in sorted(favorite_languages.keys()): # 函数 sorted() 字母正序,参数为字典.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.
# 遍历字典中的所有值
print('The following languages have been mentioned:')
for language in favorite_languages.values(): # 方法 .values() 提取字典的值,赋值到变量中
print(language.title())
# >>> The following languages have been mentioned:
# >>> Python
# >>> C
# >>> Ruby
# >>> Python
for language in set(favorite_languages.values()): # 集合 set() ,让python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
# 提取字典中不同的元素,此处提取不同的值。
print(language.title())
# >>> Python
# >>> C
# >>> Ruby
# 可使用一对花括号{}直接创建集合,并在其中使用逗号分隔元素
languages = {'python', 'C', 'jave', 'c++'}
print(languages)
# >>> {'c++', 'python', 'jave', 'C'}
例 4 字典与列表
- 字典中存储列表,可将列表与字典中的“键”相关联。
# 例 4
# 字典中存储列表
pizza ={ # 创建列表
'crust': 'thick',
'toopings': ['mushrooms', 'extra cheese'] # 键与列表相关联
}
print(f"You ordered a {pizza['crust']}-crust pizza " # 字符串很长可以在合适位置分行,每行末尾添加 引号
'with the following toppings:') # 其他行,行首进行缩进+引号
for tooping in pizza['toopings']: # 遍历字典中包含列表的键
print(tooping)
# >>> You ordered a thick-crust pizza with the following toppings:
# >>> mushrooms
# >>> extra cheese
#存储多个列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell']
}
for name, languages in favorite_languages.items():#遍历键值对
if len(languages) > 1: # 判断值len()返回的列表元素个数是否大于1
print(f"\n{name.title()}'s favorite languages are:")
for language in languages: # 遍历列表
print(f'\t{language.title()}')
elif len(languages) == 1:
print(f"Sarah's favorite language is {languages[0]}.") # 打印列表元素,因为判断元素个数等于1,所以索引为0
# >>> Jen's favorite languages are:
# >>> Python
# >>> Ruby
# >>> Sarah's favorite language is c.
# >>> Edward's favorite languages are:
# >>> Ruby
# >>> Go
# >>> Phil's favorite languages are:
# >>> Python
# >>> Haskell
例 5 字典与字典
- 采用嵌套结构,字典中存储字典。
# 例 5
# 在字典中存储字典
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.title()}') # 打印字典中的键(用户名)
full_name = f"{user_info['first']} {user_info['last']}" # 将字典中嵌套字典的键值赋值到变量
location = user_info['location']
print(full_name.title()) # 打印用户姓名
print(location.title()) # 打印用户地址
# >>> Username:Aeinstein
# >>> Albert Einstein
# >>> Princeton
# >>> Username:Mcurie
# >>> Marie Curie
# >>> Paris
例 6 嵌套拓展
- 多个字典存储到列表
# 例 6
# 嵌套
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_1 = [] # 创建一个空列表
for alien_numbers in range(30): # 遍历循环30次
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} # 创建一个新的字典
aliens_1.append(new_alien) # 将字典加入到 空列表 的末尾
for alien_1 in aliens_1[: 3]: # 遍历列表中前三个字典
if alien_1['color'] == 'green': # 若是字典中的键为绿色
alien_1['color'] = 'yellow' # 修改字典键的值
alien_1['speed'] = 'medium'
alien_1['points'] = 10
for alien_1 in aliens_1[: 5]: # 遍历输出列表中前5个字典
print(alien_1)
# >>> {'color': 'yellow', 'points': 10, 'speed': 'medium'}
# >>> {'color': 'yellow', 'points': 10, 'speed': 'medium'}
# >>> {'color': 'yellow', 'points': 10, 'speed': 'medium'}
# >>> {'color': 'green', 'points': 5, 'speed': 'slow'}
# >>> {'color': 'green', 'points': 5, 'speed': 'slow'}
print(f'Total number of aliens_1: {len(aliens_1)}') # len() 确定元素,个数、长度
# >>> Total number of aliens_1: 30
感谢,每一位认真阅读到这里的少侠!来个手滑三联吧,不迷路~
字典这一章絮絮叨叨的写的有点多了,其他的章节后续再更~
下期见,等你哟~