dictionary
我们都曾经使用过语言词典来查找不认识的单词的定义。语言词典针对给定的单词(比如 python)提供一组标准的信息。这种系统将定义和其他信息与实际的单词关联(映射)起来。使用单词作为键定位器来寻找感兴趣的信息。这种概念延伸到 Python 编程语言中,就成了特殊的容器类型,称为 dictionary。
dictionary 数据类型在许多语言中都存在。它有时候称为关联 数组(因为数据与一个键值相关联),或者作为散列表。但是在 Python 中,dictionary 是一个很好的对象,因此即使是编程新手也很容易在自己的程序中使用它。按照正式的说法,Python 中的 dictionary 是一种异构的、易变的映射容器数据类型。
创建 dictionary
本系列中前面的文章介绍了 Python 编程语言中的一些容器数据类型,包括 tuple、string 和 list(参见 参考资料)。这些容器的相似之处是它们都是基于序列的。这意味着要根据元素在序列中的位置访问这些集合中的元素。所以,给定一个名为 a 的序列,就可以使用数字索引(比如 a[0] )或片段(比如 a[1:5])来访问元素。Python 中的 dictionary 容器类型与这三种容器类型的不同之处在于,它是一个无序的集合。不是按照索引号,而是使用键值来访问集合中的元素。这意味着构造 dictionary 容器比 tuple、string 或 list 要复杂一些,因为必须同时提供键和相应的值,如清单 1 所示。
清单 1. 在 Python 中创建 dictionary,第 1 部分
>>> d = {0: 'zero', 1: 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5: 'five'}
>>> d
{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> len(d)
>>> type(d) # Base object is the dict class
<type 'dict'>
>>> d = {} # Create an empty dictionary
>>> len(d)
>>> d = {1 : 'one'} # Create a single item dictionary
>>> d
{1: 'one'}
>>> len(d)
>>> d = {'one' : 1} # The key value can be non-numeric
>>> d
{'one': 1}
>>> d = {'one': [0, 1,2 , 3, 4, 5, 6, 7, 8, 9]}
>>> d
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
如这个例子所示,在 Python 中创建 dictionary 要使用花括号和以冒号分隔的键-值组合。如果没有提供键-值组合,那么就会创建一个空的 dictionary。使用一个键-值组合,就会创建具有一个元素的 dictionary,以此类推,直至您需要的任何规模。与任何容器类型一样,可以使用内置的 len 方法查明集合中元素的数量。
前面的示例还演示了关于 dictionary 容器的另一个重要问题。键并不限制为整数;它可以是任何不易变的数据类型,包括 integer、float、tuple 或 string。因为 list 是易变的,所以它不能作为 dictionary 中的键。但是 dictionary 中的值可以是任何数据类型的。
最后,这个示例说明了 Python 中 dictionary 的底层数据类型是 dict 对象。要进一步了解如何使用 Python 中的 dictionary,可以使用内置的帮助解释器来了解 dict 类,如清单 2 所示。
清单 2. 获得关于 dictionary 的帮助
>>> help(dict)on class dict in module __builtin__:
dict(object)
| dict() -> new empty dictionary.
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs.
| dict(seq) -> new dictionary initialized as if via:
| d = {}
| for k, v in seq:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __cmp__(...)
| x.__cmp__(y) <==> cmp(x,y)
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
...
关于 dict 类的帮助指出,可以使用构造函数直接创建 dictionary,而不使用花括号。既然与其他容器数据类型相比,在创建 dictionary 时必须提供更多的数据,那么这些创建方法比较复杂也就不足为奇了。但是,在实践中使用 dictionary 并不难,如清单 3 所示。
清单 3. 在 Python 中创建 dictionary,第 2 部分
>>> l = [0, 1,2 , 3, 4, 5, 6, 7, 8, 9]
>>> d = dict(l)(most recent call last):
File "<stdin>", line 1, in ?: can't convert dictionary
update sequence element #0 to a sequence
>>> l = [(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')]
>>> d = dict(l)
>>> d
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> l = [[0, 'zero'], [1, 'one'], [2, 'two'], [3, 'three']]
>>> d
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> d = dict(l)
>>> d
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>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