字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、只含不可变类型元素的元组(1,2,3,’abc’)、实现__hash__()方法的自定义对象(因为__hash__()须返回一个整数,否则会出现异常:TypeError: an integer is required)。可以用hash(obj)检测对象是否是可哈希的。
>>> class HashEnable(object): ... def __hash__(self): ... return 1>>> he = HashEnable()
>>> hash(he) 1 >>> d = {he:1} >>> d = {['1',2]:2} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
(1)创建字典
>>> d1 = {} >>> d2 = {'player':'QVOD','game':'kw'} >>> d1,d2 ({}, {'player': 'QVOD', 'game': 'kw'}) >>> d3 = dict((['name','alex'],['sex','man'])) >>> d3 {'name': 'alex', 'sex': 'man'} >>> d33 = d3.copy() >>> d33 {'name': 'alex', 'sex': 'man'} >>> d4 = {}.fromkeys(('alex','zhou'),1) >>> d4 {'alex': 1, 'zhou': 1} >>> d5 = {}.fromkeys(('alex','zhou')) >>> d5 {'alex': None, 'zhou': None}
>>> d = {'name':'alexzhou','sex':'man'} >>> for key in d: ... print '%s,%s' %(key,d[key]) ... name,alexzhou sex,man >>> d['name'] 'alexzhou' >>> d2 = {'name':'alexzhou','age':100} >>> print 'name: %s,age: %d' %(d2['name'],d2['age']) name: alexzhou,age: 100 >>> d2['sex'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'sex' >>> 'sex' in d2 False >>> 'name' in d2 True
>>> d = {'name':'alexzhou','age':100} >>> d['age'] = 88 >>> d {'age': 88, 'name': 'alexzhou'} >>> d.pop('age') 88 >>> d {'name': 'alexzhou'} >>> d.clear() >>> d {}
(1)cmp()
字典的比较:首先是字典的大小,然后是键,最后是值
>>> d1 = {'abc':1,'efg':2} >>> d2 = {'abc':1,'efg':2,'h':3} >>> cmp(d1,d2) -1 >>> d3 = {'ab':1,'efg':2} >>> cmp(d1,d3) 1 >>> d4 = {'abc':1,'efg':3} >>> cmp(d1,d4) -1 >>> d5 = {'abc':1,'efg':2} >>> cmp(d1,d5) 0
>>> d = {'abc':1,'efg':2} >>> len(d) 2(3)keys()、values() 、items()
>>> d = {'name':'alex','sex':'man'} >>> d.keys() ['name', 'sex'] >>> d.values() ['alex', 'man'] >>> d.items() [('name', 'alex'), ('sex', 'man')]
>>> d = {'name':'alex','sex':'man'} >>> d.get('name','not exists') 'alex' >>> d.get('alex','not exists') 'not exists'
>>> d.setdefault('name','zhou') 'alex' >>> d {'name': 'alex', 'sex': 'man'} >>> d.setdefault('haha','xixi') 'xixi' >>> d {'haha': 'xixi', 'name': 'alex', 'sex': 'man'}
>>> d = {'name':'alex','sex':'man'} >>> d1 = {'age':100,'address':'shenzhen'} >>> d.update(d1) >>> d {'age': 100, 'address': 'shenzhen', 'name': 'alex', 'sex': 'man'}(7)sorted(dict)
>>> sorted(d) ['address', 'age', 'name', 'sex']
python中集合对象(set)是一组无序排列的可哈希的值,包含两种类型:可变集合(set)和不可变集合(frozenset),所以set不是可哈希的,frozenset是可哈希的,能当作字典的键。
>>> s = set('a') >>> hash(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set' >>> fs = frozenset('a') >>> hash(fs) -1305064881317614714
(1)创建集合
>>> s = set('alexzhou') >>> s set(['a', 'e', 'h', 'l', 'o', 'u', 'x', 'z']) >>> fs = frozenset('alexzhou') >>> fs frozenset(['a', 'e', 'h', 'l', 'o', 'u', 'x', 'z'])
>>> for e in s: ... print e ... a e h l o u x z
>>> s = set('alexzhou') >>> s.update('hai') >>> s set(['a', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z']) >>> s.add('hai') >>> s set(['a', 'hai', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z']) >>> s.remove('hai') >>> s set(['a', 'e', 'i', 'h', 'l', 'o', 'u', 'x', 'z']) >>> s -= set('alex') >>> s set(['i', 'h', 'o', 'u', 'z']) >>> s.pop() 'i' >>> s set(['h', 'z', 'u', 'o']) >>> s.discard('h') >>> s set(['z', 'u', 'o']) >>> s.clear() >>> s set([]) >>> fs = frozenset('alexzhou') >>> fs.add('z') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add'
>>> s = set('alexzhou') >>> fs = frozenset('alexzhou') >>> s == fs True >>> s2 = set('alexzhou') >>> s == s2 True >>> s3 = set('alexzhouj') >>> s > s3 False >>> s < s3 True >>> s
>>> s1 = set('abc') >>> fs = frozenset('de') >>> s1 | fs set(['a', 'c', 'b', 'e', 'd']) >>> type(s1 | fs) <type 'set'> >>> type(fs | s1) <type 'frozenset'> >>> s2 = set('fg') >>> type(s1 | s2) <type 'set'> >>> s1.union(fs) set(['a', 'c', 'b', 'e', 'd']) >>> type(s1.union(fs)) <type 'set'="" class="last"> >>> type(fs.union(s1)) <type 'frozenset'="" class="last"> </type></type>(6)交集s1&s2,补集s1-s2,异或s1^s2交集:新集合中的元素同时是s1和s2的元素 –> s1.intersection(s2)补集:新集合中的元素只属于s1,不属于 –> s1.difference(s2)异或:新集合中的元素不能同时属于s1和s2 –> s1.symmetric_difference(s2)
>>> fs = frozenset('de') >>> s = set('def') >>> s & fs set(['e', 'd']) >>> s - fs set(['f']) >>> fs - s frozenset([]) >>> s ^ fs set(['f']) >>> s.intersection(fs) set(['e', 'd']) >>> s.difference(fs) set(['f']) >>> s.symmetric_difference(fs) set(['f'])