
9-1 字典基本操作
9-1-1 定义字典
字典也是一个列表型的数据结构,但是它的元素是用“键-值”方式配对存储,在操作时是用键(key)取得值(value)的内容。定义字典时,是将键-值放在大括号“{ }”内,字典的语法格式如下:
name_dict = { 键1:值1, … , 键n:值n } # name_dict是字典变量名称
字典的值(value)可以是任何Python的对象,所以可以是数值、字符串、列表等。
程序实例ch9_1.py:以水果行和面店为例定义一个字典,同时列出字典。下列字典是设定水果一斤的价格、面一碗的价格,最后使用type( )列出字典数据类型。

执行结果

在使用Python设计打斗游戏时,玩家通常扮演英雄的角色,敌军可以用字典方式存储,例如,可以用不同颜色的标记设定敌军的小兵,每一个敌军的小兵给予一个分数,这样可以由打死敌军数量再统计游戏得分,可以用下列方式定义字典内容。
程序实例ch9_2.py:定义soldier0字典tag和score是键,red和3是值。

执行结果

上述是定义红色(red)小兵,分数是3分,玩家打死红色小兵得3分。
9-1-2 列出字典元素的值
字典的元素是“键-值”配对设定,如果想要取得元素的值,可以将键当作是索引方式处理,因此字典内的元素不可有重复的键,可参考下列实例ch9_3.py的第4行,例如,下列可传回fruits字典水蜜桃键的值。
fruits[‘水蜜桃'] # 用字典变量[‘键']取得值
下列是完整实例。
程序实例ch9_3.py:分别列出ch9_1.py中水果店水蜜桃一斤的价格和面店牛肉面一碗的价格。

执行结果

程序实例ch9_4.py:分别列出ch9_2.py小兵字典的tag和score键的值。

执行结果

9-1-3 增加字典元素
可使用下列语法格式增加字典元素:
name_dict[键] = 值# name_dict是字典变量
程序设计ch9_5.py:为fruits字典增加橘子一斤18元。

执行结果

在设计打斗游戏时,我们可以使用屏幕坐标标记小兵的位置,下列实例是用xpos/ypos标记小兵的x坐标/y坐标。
程序实例ch9_6.py:为soldier0字典增加x,y轴坐标(xpos,ypos)和移动速度(speed)元素,同时列出结果做验证。

执行结果

9-1-4 更改字典元素内容
市面上的水果价格是浮动的,如果发生价格异动可以使用本节观念更改。
程序实例ch9_7.py:将fruits字典的香蕉一斤改成12元。

执行结果

在设计打斗游戏时,我们需要时刻移动小兵的位置,此时可以使用本节介绍的方法来更改小兵位置。
程序实例ch9_8.py:依照soldier字典speed键的值移动小兵位置。

执行结果

上述程序将小兵移动速度分成3个等级,slow是每次xpos移动1单位(5和6行),medium是每次xpos移动3单位(7和8行),另一等级则是每次xpos移动5单位(9和10行)。第11行是执行小兵移动,为了简化条件y轴暂不移动。所以可以得到上述小兵x轴位置由100移到101。
9-1-5 删除字典特定元素
如果想要删除字典的特定元素,它的语法格式如下:
del name_dict[键] # 可删除特定键的元素
程序实例ch9_9.py:删除fruits字典的西瓜元素。

执行结果

9-1-6 删除字典所有元素
Python有提供方法clear( )可以将字典的所有元素删除,此时字典仍然存在,不过将变成空的字典。
程序实例ch9_10.py:使用clear( )方法删除fruits字典的所有元素。

执行结果

9-1-7 删除字典
Python也有提供del指令可以将整个字典删除,字典一经删除就不再存在。它的语法格式如下:
del name_dict# 可删除字典name_dict
程序实例ch9_11.py:删除字典的测试,这个程序前4行是没有任何问题,第5行尝试打印已经被删除了的字典,所以产生错误,错误原因是没有定义fruits字典。

执行结果

9-1-8 建立一个空字典
在程序设计时,也允许先建立一个空字典,建立空字典的语法如下:
name_dict = { }# name_dict是字典名称
上述建立完成后,可以用9-1-3节增加字典元素的方式为空字典建立元素。
程序实例ch9_12.py:建立一个小兵的空字典,然后为小兵建立元素。

执行结果

9-1-9 字典的复制
在大型程序开发过程,有时为了要保护原先字典内容,所以常会需要将字典复制,此时可以使用此方法。
new_dict = name_dict.copy( )# name_dict会被复制至new_dict
上述所复制的字典是独立存在新地址的字典。
程序实例ch9_13.py:复制字典的应用,同时列出新字典所在地址,如此可以验证新字典与旧字典是不同的字典。

执行结果

9-1-10 取得字典元素数量
在列表(list)或元组(tuple)使用的方法len( )也可以应用在字典,它的语法如下:
length = len(name_dict)# 将返回name_dict字典的元素数量给length
程序实例ch9_14.py:列出空字典和一般字典的元素数量,本程序第4行由于是建立空字典,所以第7行印出元素数量是0。

执行结果

9-1-11 验证元素是否存在
可以用下列语法验证元素是否存在。
键 in name_dict# 可验证键元素是否存在
程序实例ch9_15.py:这个程序会要求输入键-值,然后判断此元素是否在fruits字典,如果不在此字典则将此键-值加入字典。

执行结果

9-1-12 设计字典的可读性技巧
设计大型程序时,字典的元素内容很可能是由长字符串所组成,碰上这类情况建议从新的一行开始安置每一个元素,如此可以大大增加字典内容的可读性。例如,有一个players字典,元素是由键(球员名字)-值(球队名称)所组成。如果,我们使用传统方式设计,将让整个字典定义变得很复杂,如下所示:

碰上这类字典,建议是一行定义一个元素,如下所示:

程序实例ch9_16.py:字典元素是长字符串的应用。

执行结果
