字典

字典

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字典
>>> dict2
Traceback (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
{}
>>> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值