字典
-
字典的创建:
-
创建一个空字典:dict1 = { }
-
一般创建字典方法:dict1 = {1:‘one’,2:‘two’,3:‘three’}
-
通过映射关系创建字典:dict1 = dict( ( (1,‘one’), (2,‘two’), (3,‘three’) ) )或者dict1 = dict( [ (1,‘one’), (2,‘two’), (3,‘three’) ] )或者dict1 = dict( [ [1,‘one’], [2,‘two’], [3,‘three’] ] )
其中,最里面的几组小括号或者中括号是表示映射关系,第二层的小括号或中括号是将其组合成元组或列表,然后使用
dict()
函数根据映射关系创建字典。>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2})
-
-
字典的内建方法:
-
dict.fromkeys(S[ ,v]) -> New dict with keys from S and values equal to v(v default to None)
>>> dict.fromkeys((1, 2, 3), ('one', 'two', 'three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
-
访问字典的几个方法:keys()、values()、items()
keys()返回字典键的引用,values()返回字典值的引用,items()返回字典项的引用
-
使用get()内建函数:也可以在get中为不存在的项输出相应的提示
-
如果不知道一个键是否在字典中(不能查找值),可以使用成员资格操作符来进行判断。in 和 not in
-
清空一个字典,使用clear()方法。
-
copy()拷贝,区别于赋值
-
pop()和popitem(),都是弹出字典中的元素。pop()是弹出对应键的项,返回键对应的值,popitem()是随机从字典弹出项,返回键和值的元组。
-
setdefault():用法与get()类似,只是如果找不到对应的键,会自动添加,值默认为None,也可以给值。
-
update(),用一个字典或映射关系去更新一个字典。
-
集合
- 集合的特点:唯一性,无序性
- 如何创建一个集合:直接把一堆元素用大括号括起来或者使用工厂函数set()
- 内置函数 add() 和 remove()
- frozenset() :定义不可变集合