第 6 章主要练习了各种字典,以下内容
什么是字典
字典中 键-值 的关系
一个简单的字典
通过字典中的键查找其对应的值
在字典中添加 键-值
修改字典中的值
遍历字典中的键值对 items( )
遍历字典中的键 keys( )
遍历字典中的值 value( )
遍历字典中的值并且去重复 set( )
列表中嵌套字典
通过 for 循环将字典添加到同一个列表中
在字典中存储列表并打印
什么是字典?
我自己来个不成熟的总结吧:就是一个高级列表,为啥说是高级列表,因为列表中的元素是单一的,没有属性
而字典可以指定属性。比如说:你叫张三,在列表中只能存储张三这个姓名,而字典可以储存为 --- 姓名:张三
字典使用花括号 { }
列表使用中括号 [ ]
元组使用小括号 ( )
字典中的 键-值 关系
比如这个简单的列表 alien_0 = {‘color‘: ‘green‘, ‘points‘: 5}
color 是键,green 是值
一个简单的字典
通过 键 获取相关的 值
------------------------------------------------
alien_0 = {‘color‘: ‘green‘, ‘points‘: 5}
print(alien_0[‘color‘])
print(alien_0[‘points‘])
------------------------------------------------
green
5
如何引用的字典中的值
将通过字典中的键获取到的值定义一个变量,并在 print 中引用
------------------------------------------------------------------------
alien_0 = {‘color‘: ‘green‘, ‘points‘: 5}
new_points = alien_0[‘points‘]
print("You just earned " + str(new_points) + " points!")
------------------------------------------------------------------------
You just earned 5 points!
添加 键-值
在 alien_0 字典中在添加两个键值对
----------------------------------------------------------------------------
alien_0 = {‘color‘: ‘green‘, ‘points‘: 5}
print(alien_0)
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‘}
print("The alien is " + alien_0[‘color‘] + ".")
alien_0[‘color‘] = ‘yellow‘
print("The alien is now " + alien_0[‘color‘] + ".")
---------------------------------------------------------------
The alien is green.
The alien is now yellow.
删除键值对
和列表相同,使用 del 删除字典中的键值(永久性删除)
------------------------------------------------
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‘,
}
print("Sarah‘s favorite language is " + favorite_languages[‘sarah‘].title() + ".")
-------------------------------------------------------------------------------------------
Sarah‘s favorite language is C.
items( ) 遍历所有的键值对
可以通过一个简单的 for 循环遍历这个字典
-----------------------------------------
user_0 = {
‘username‘: ‘efermi‘,
‘first‘: ‘enrico‘,
‘last‘: ‘fermi‘,
}
for key, value in user_0.items():
print("\nKey: " + key)
print("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(name.title() + "‘s favorite language is " + language.title() + ".")
-------------------------------------------------------------------------------------------
Jen‘s favorite language is Python.
Sarah‘s favorite language is C.
Edward‘s favorite language is Ruby.
Phil‘s favorite language is Python.
keys( ) 遍历字典所有的键
其实不加 keys() 也没关系,因为字典默认就会遍历所有的键
这样更清楚而已
--------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
for name in favorite_languages.keys():
print(name.title())
---------------------------------------------------
Jen
Sarah
Edward
Phil
使用 for 循环遍历字典中内容
并定义一个列表做 if 判断,如果 for 循环中有列表的元素
就在打印一句话
-------------------------------------------------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
friends = [‘phil‘, ‘sarah‘]
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")
-------------------------------------------------------------------------------------------
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!
使用 keys() 遍历,检查字典中的 键 是不是存在指定的字符,并做 if 判断
如果 erin 不存在字典中,就指定 print
-----------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
if ‘erin‘ not in favorite_languages.keys():
print("Erin, please take our poll!")
------------------------------------------------------
Erin, please take our poll!
按顺序遍历字典中的所有键
调用 sorted( ) 进行排序
-------------------------------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
for name in sorted(favorite_languages.keys()):
print(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.
value( ) 遍历字典中的所有值并大写
---------------------------------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
---------------------------------------------------------------------------
The following languages have been mentioned:
Python
C
Ruby
Python
在数据比较多的情况下,可以使用 set( ) 去除重复项
set( ) 合集
--------------------------------------------------------------------------
favorite_languages = {
‘jen‘: ‘python‘,
‘sarah‘: ‘c‘,
‘edward‘: ‘ruby‘,
‘phil‘: ‘python‘,
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
--------------------------------------------------------------------------
The following languages 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}
使用循环创建字典列表
for 循环 30 次,将 new_alien 的字典放到 aliens 列表中
打印前 5 次
用 len( ) 计算 aliens 列表的长度
---------------------------------------------------------------------------
aliens = []
for alien_number in range(30):
new_alien = {‘color‘: ‘green‘, ‘points‘: 5, ‘speed‘: ‘slow‘}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(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
在字典循环中进行比较并更改值
先定义一个空列表 aliens,将 new_alien 的列表循环 30 次加到 aliens 列表中
第二个 for 循环先对 aliens 切片,进行判断
== 是进行比较
= 是进行更改
第三个 for 循环是打印 aliens 列表的前 5 个元素,可以看出修改后的不同
----------------------------------------------------------------------------
aliens = [ ]
for alien_number in range(30):
new_alien = {‘color‘: ‘green‘, ‘points‘: 5, ‘speed‘: ‘slow‘}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien[‘color‘] == ‘green‘:
alien[‘color‘] = ‘yellow‘
alien[‘speed‘] = ‘medium‘
alien[‘points‘] = 10
for alien in aliens[0:5]:
print(alien)
print("...")
----------------------------------------------------------------------------
{‘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‘}
...
在字典中存储列表
在 pizza 字典中 toppings 列表中有两个值,都可以分别打印
------------------------------------------------------------------------------------------------------------------
pizza = {
‘crust‘ : ‘thick‘,
‘toppings‘ : [‘mushrooms‘, ‘extra cheese‘]
}
print("You ordered a " + pizza[‘crust‘] + "-crust pizza " + "with the following toppings:")
for topping in pizza[‘toppings‘]:
print("\t" + topping)
------------------------------------------------------------------------------------------------------------------
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
对字典进行 for 循环,在将字典中的列表的元素再次进行循环
-------------------------------------------------------------------------------
favorite_languages = {
‘jen‘: [‘python‘, ‘ruby‘],
‘sarah‘: [‘c‘],
‘edward‘: [‘ruby‘, ‘go‘],
‘phil‘: [‘python‘, ‘haskell‘],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "‘s favorite languages are:")
for language in languages:
print("\t" + language.title())
-------------------------------------------------------------------------------
Jen‘s favorite languages are:
Python
Ruby
Sarah‘s favorite languages are:
C
Edward‘s favorite languages are:
Ruby
Go
Phil‘s favorite languages are:
Python
Haskell