PS:注意mapping type中的dict就是转换成dictionary数据结构。
通常我们理解dictinary都是认为是"associative memories" or "associative arrays".
同时,我们一般所用的sequence都是用number作为indexes的,而这里dictionary都是用'key'作为indexes,同时dictionary是unordered。
keys我们一般使用string或者number,或者tuples(注意,这里用作的key的都是不可以改变的immutable type,例如list就不能,因为有assignment)
空字典:{}
格式: key:value
分隔符: ,
对于dictionary的操作,我们一般使用key作为storing或者extracting或者del 字典的元素。
字典的常用操作:keys() sorted() values()
实例:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
创建dictionary的三种形式:
1)直接使用dict()函数,可以使得直接从key-value对的序列而产生(包括list)
① dict(iterable)
PS:sequence, a container that can be iterated on, to get a finite number of items, one at a time, and that also supports indexing, slicing, and being passed to the built-in functin len.
dict() constructor builds dictionary directly from sequences of key-value pairs:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
② dict(**args)
例如
>>> dict(sape=4139,guido=417,jack=4127)
{'sape': 4139, 'jack': 4098, 'guido': 4127}