6.1 一个简单的字典
>>> alien_0 = {'color':'green','point':5}
>>> alien_0
{'color': 'green', 'point': 5}
6.2 使用字典
在Python中,字典是一系列键-值
对,可将任何Python对象用作字典中的值。
6.2.1 访问字典中的值
>>> alien_0['color']
'green'
6.2.2 添加键-值对
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> alien_0
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
6.2.3 先创建一个空子典
>>> alien_0 = {}
>>> alien_0 = dict()
>>> alien_0
{}
6.2.4 修改字典中的值
>>> alien_0
{'color': 'green', 'point': 5}
>>> alien_0['color'] = 'yellow'
>>> alien_0
{'color': 'yellow', 'point': 5}
6.2.5 删除键-值对
>>> del alien_0['point']
>>> alien_0
{'color': 'yellow'}
6.3 遍历字典
6.3.1 遍历所有键-值对
使用 key,val in dict.items():
句式来遍历字典,items()
返回一个键-值对列表。
>>> user_0 = {
... 'username':'efermi',
... 'first':'enrico',
... 'last':'fermi',
... }
>>> for key,val in user_0.items():
... print(key)
... print(val)
...
username
efermi
first
enrico
last
fermi
6.3.2 遍历字典中的所有键
使用方法keys()
遍历字典中的键。
>>> for key in user_0.keys():
... print(key)
...
username
first
last
6.3.3 按顺序遍历字典中的所有键
使用sorted
函数来获得按特定顺序排列的键列表的副本:
>>> for name in sorted(user_0.keys()):
... print(name)
...
first
last
username
6.3.4 遍历字典中的所有值
使用方法values()
返回字典中的所有值。
>>> for val in user_0.values():
... print(val)
...
efermi
enrico
fermi