目录
2.3 按顺序输出字典中所有键 sorted(dictionary.keys())
1. 使用字典
字典是一系列 键-值 对。每个键都与一个值相关联,可以通过键访问相关的值。
与键相关的值可以使数字、字符串、列表、字典,事实上,可以将任何python对象用作字典中的值。
字典使用花括号{ }表示。
alien_o = {"color" : "green", "point" : 5}
1.1 访问字典中的值
alien_0 = {"color" : "green", "point" : 5}
print(alien_0["color"])
1.2 添加键-值对
>>> alien_0 = {"color" : "green", "point" : 5}
>>> print(alien_0)
{'color': 'green', 'point': 5}
#添加x和y坐标位置
>>> alien_0["x_position"]=0
>>> alien_0["y_position"]=25
>>> print(alien_0)
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}
1.3 先创建一个空字典
有时候需要新建一个空字典,之后再添加各个键-值对。
>>> alien_0={}
>>>
>>> alien_0["color"] = "green"
>>> alien_0["point"] = 5
>>> print(alien_0)
{'color': 'green', 'point': 5}
1.4 修改字典中的值
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original position: " + str(alien_0['x_position']))
# Move the alien to the right.
# Figure out how far to move the alien based on its speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien.
x_increment = 3
# The new position is the old position