字典
1、字典
字典属于映射类型。字典使用大括号({ }),{key,value}
(1)创建字典和给字典赋值
>>> dict1={}
>>> dict2={'name':'earth','port':80}
>>> print dict2
{'name': 'earth', 'port': 80}
>>> type(dict2)
<type 'dict'>
>>> dict1,dict2
({}, {'name': 'earth', 'port': 80})
(2)使用dict()方法创建字典
>>> fdict=dict((['x',1],['y',2]))
>>> fdict
{'y': 2, 'x': 1}
(3)使用內建方法fromkeys()创建字典
>>> ddict={}.fromkeys(('x','y'),-1)
>>> ddict
{'y': -1, 'x': -1}
>>> edict={}.fromkeys(('foo','bar')) >>> edict {'foo': None, 'bar': None}
(4)访问字典中的值
遍历一个字典(一般用键),只需要循环查看它的键即可:
>>> dict2={'name':'earth','port':80} >>> for key in dict2.keys(): print 'keys=%s,values=%s' %(key,dict2[key]) keys=name,values=earth keys=port,values=80
>>> for key in dict2: print 'keys=%s,values=%s' %(key,dict2[key]) keys=name,values=earth keys=port,values=80 >>> dict2['name'] 'earth'
2、常用方法
(1)has_key()
>>> dict2={'name':'earth','port':80} >>> dict2.has_key('server') False >>> dict2.has_key('name') True
(2)in
>>> dict2={'name':'earth','port':80} >>> 'server' in dict2 False >>> 'name' in dict2 True
(3)not in
>>> dict2={'name':'earth','port':80} >>> 'name' not in dict2 False >>> 'server' not in dict2 True
(4)字典中数字和字符串混用的例子
>>> dict3={} >>> dict3[1]='abc' >>> dict3['1']='3.14' >>> dict3[3.2]='xyz' >>> dict3 {'1': '3.14', 1: 'abc', 3.2: 'xyz'}
整体赋值:
>>> dict3={1:'abc','1':'3.14',3.2:'xyz'} >>> dict3 {'1': '3.14', 1: 'abc', 3.2: 'xyz'}
4、更新字典
(1)添加新数据项
>>> dict2={'name':'earth','port':80} >>> dict2['name']='venus' >>> dict2['arch']='sunos5' >>> dict2 {'arch': 'sunos5', 'name': 'venus', 'port': 80}
(2)删除字典元素和字典
>>> dict2 {'arch': 'sunos5', 'name': 'venus', 'port': 80} >>> del dict2['name'] #删除键为'name'的条目 >>> dict2 {'arch': 'sunos5', 'port': 80}
>>> del dict2 #删除整个dict2字典 >>> dict2Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
dict2
NameError: name 'dict2' is not defined
>>> dict2={'name':'earth','port':80} >>> dict2.pop('name') #删除并返回键为‘name’的条目 'earth' >>> dict2 {'port': 80}
>>> dict2.clear() #删除dict2中所有条目 >>> dict2 {} >>>