导文
字典类型的容器在编程中的重要性不再言谈,通过现有典型互联网企业及传统企业专门部署redis集群服务器可知字典的编程、业务应用方面的重要性。
字典定义及初始化
- 非线性结构容器
- key-value键值对的数据集合
- 可变的,无须的,key不重复
- key值必须可hash
1.If no positional argument is given, an empty dictionary is created
当没有位置参数给定时,一个空的字典被创建
2.If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object.
当位置参数给定时,而且是一个映射对象,字典被创建,key-value是映射对象组
3.the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.
当位置参数是可迭代对象时,每一个item必须有两个值,第一个值在字典中为key,第二个值在字典中为value
4.If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
如果一个key重复出现,最后一个值覆盖之前的key值
- class dict(**kwarg)
此类方法构建字典时,通常采用name=value初始化一个字典,即key-value的映射,而此类方法要注意如下代码写法
#!/bin/python3
#-*- coding: UTF-8 -*-
#忌讳dict("a"=1,"b"=2),因为字符串对象不能接受赋值,而a=1,b=2才可以正常定义变量及赋值
dic = dict(a=1,b=2,c=3)
print(dic)
- class dict(mapping,**kwarg)
此类方法构建字典时,通常采用函数或其他关系映射为二元组的数据
#!/bin/python3
#-*- coding: UTF-8 -*-
dic = dict(zip(['one','two','three'],[1,2,3]))
print(dic)
- class dict(iterable,**kwarg)
此类方法是通过可迭代对象,可迭代对象必须为二元组,但是二元组中key值必须可hash
错误代码示范:
#!/bin/python3
#-*- coding: UTF-8 -*-
#key值出现不可hash值
dic = dict([(["a","b"],10),("c",20)])
print(dic)
运行结果:
Traceback (most recent call last):
File "./dic.py", line 4, in <module>
dic = dict([(["a","b"],10),("c",20)])
TypeError: unhashable type: 'list'
正确代码示范