
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
6.1 创建字典
在Python中字典是一种可变容器模型,可以存储任意类型的对象,通过字典可以描述一个事物的多种特征。
6.1.1 创建最基本的字典
字典是通过花括号“{}”来创建的,它的内部由零到多个键值(key-->value)组成,单个键值内部对通过冒号“:”将键和值隔开,多个键值用逗号“,”隔开。关于字典的描述可能还比较抽象,如果通过代码来声明图6-1中的A点和B点,就会更直观。对应的代码如下所示:

运行上述代码得到的输出结果如下:

需要注意的是,在字典中键是唯一的,如果声明多个相同的键,那么Python只会保留最后的那个键的值,如下所示:

加粗的代码创建的是A点,但是前面的键值是“"x": 2”,后面的键值是“"x": 1”,此时在Python中会用后者覆盖前者,所以最后采用的是“"x": 1”。
6.1.2 创建空字典
创建一个空字典有两种方式,如下所示:

注意 不要混淆空集合和空字典的创建
集合的创建也是使用花括号“{}”。初学者容易混淆空集合和空字典的创建,请注意下面的代码:

加粗的代码是在创建字典,而不是集合。如果运行上述代码,那么得到的输出结果如下:

6.1.3 使用内置函数dict创建字典
实际上,可以使用Python的内置函数dict创建字典,一般来说使用dict函数有3种方式,下面举例说明,如代码清单6-1所示。
代码清单6-1:使用Python的内置函数dict创建字典


代码①处使用赋值参数创建字典,这种方式的好处是比较直观。代码②处使用zip函数和列表组合映射创建字典,这种方式比较复杂,也不直观,因此笔者不推荐使用这样的方式创建字典。代码③处使用列表和元组组合创建字典,这种方式适合创建键值较多的字典。