创建字典
>>> 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}
遍历字典
ps:访问一个不存在的key时,会发生KeyError异常,访问前可使用in或not in判断一下。
d={“name”:”python”,”english”:33,”math”:35}
print “##for in “
for key in d:
print ‘%s,%s’ %(key,d[key])
for i in d:
print “d[%s]=” % i,dict[i]
print “##items”
for (k,v) in d.items():
print “d[%s]=” % k,v
print “##iteritems”
for k,v in d.iteritems():
print “d[%s]=” % k,v
>>> d[‘name’]
‘python’
>>> 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 “
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
{}
常用内建函数
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
len()
返回键值对的数目
>>> d = {‘abc’:1,’efg’:2}
>>> len(d)
2
keys()、values() 、items()
keys()返回一个包含字典所有键的列表
values()返回一个包含字典所有值的列表
items()返回一个包含键值元组的列表
>>> d = {‘name’:’alex’,’sex’:’man’}
>>> d.keys()
[‘name’, ‘sex’]
>>> d.values()
[‘alex’, ‘man’]
>>> d.items()
[(‘name’, ‘alex’), (‘sex’, ‘man’)]
dict.get(key,default=None)
返回字典中key对应的value,若key不存在则返回default
>>> d = {‘name’:’alex’,’sex’:’man’}
>>> d.get(‘name’,’not exists’)
‘alex’
>>> d.get(‘alex’,’not exists’)
‘not exists’
dict.setdefault(key,default=None)
若key存在,则覆盖之前的值,若key不存在,则给字典添加key-value对
>>> d.setdefault(‘name’,’zhou’)
‘alex’
>>> d
{‘name’: ‘alex’, ‘sex’: ‘man’}
>>> d.setdefault(‘haha’,’xixi’)
‘xixi’
>>> d
{‘haha’: ‘xixi’, ‘name’: ‘alex’, ‘sex’: ‘man’}
dict.update(dict2)
将字典dict2的键值对添加到dict
>>> d = {‘name’:’alex’,’sex’:’man’}
>>> d1 = {‘age’:100,’address’:’shenzhen’}
>>> d.update(d1)
>>> d
{‘age’: 100, ‘address’: ‘shenzhen’, ‘name’: ‘alex’, ‘sex’: ‘man’}
sorted(dict)
返回一个有序的包含字典所有key的列表
>>> sorted(d)
[‘address’, ‘age’, ‘name’, ‘sex’]