python:字典(Dictionary)
字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何python数据类型。
2、增加字典元素:两种方法
>>> dict1['a']=1 #第一种
#第二种:setdefault方法
>>> dict1.setdefault('b',2)
3、删除字典
#删除指定键-值对
>>> del dict1['a'] #也可以用pop方法,dict1.pop('a')
#清空字典
>>> dict1.clear() #字典变为空了
#删除字典对象
>>> del dict1
4、字典的方法
1)get(key,default=None)
返回键值key对应的值;如果key没有在字典里,则返回default参数的值,默认为None
>>> dict1 #空的字典
>>> dict1.get('a') #键‘a’在dict1中不存在,返回none
>>> dict1.get('d1','no1') #default参数给出值'no1',所以返回'no1'
>>> dict1['a']='no1' #插入一个新元素
>>> dict1.get('a') #现在键'a'存在,返回其值
'1111'
2)clear
清空字典
3)has_key(key)
如果key出现在dict里则返回True;否则返回False
>>> dict1
{'a': '1111'}
>>> dict1.has_key('b')
False
>>> dict1.has_key('a')
True
4)items
返回dict的(键,值)tuple对的一个列表
>>> dict1
{'a': 'no1', 'b': '2222'}
>>> dict1.items()
[('a', 'no1'), ('b', '2222')]
5)keys 返回dict的键列表
6)values 返回dict的值列表
>>> dict1
{'a': 'no1', 'b': '2222'}
>>> dict1.keys()
['a', 'b']
>>> dict1.values()
['no1', '2222']
7)setdefault(key,default=None)
如果dict中有key,则返回key值,如果没有找到key,则在dict中加上该key,值由default参数给出,默认None
8)update(dict2)
把dict2的元素加入到dict中去,键字重复时会覆盖dict中的键值
9)popitem
删除任意键-值对,并返回该键-值对,如字典为空,则产生异常
>>> dict1
{'b': 'no2'}
>>> dict1.popitem()
('b', 'no2')
10)pop(key,[d])
删除指定键字的键-值对,并返回该键对应的值,若key不存在,则返回d
>>> dict1
{'a': 'no1', 'c': '3333', 'b': 'no2'}
>>> dict1.pop('a')
'no1'
>>> dict1
{'c': '3333', 'b': 'no2'}
11)copy
返回字典的一个浅拷贝
12)fromkeys
fromkeys(seq[,value]) #以seq为keys,创建一个新dictionary,初始化各值为value
>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}
13)iteritems
14)iterkeys
15)itervalues
邵珠庆推荐文章
博文加载中...
2012年03月14日 11:56
There’s a dress I want..I think I will go get it now…
2012年01月15日 23:19
Outstanding blogger, Thankx for writing this prestigious blogpost. I found it informative. Kind regards !!
2012年01月29日 05:15
You know what, I’m very much icnlneid to agree.
2012年02月01日 09:47
Surprisingly well-written and informative for a free online aritlce.
2011年11月23日 12:15
Ppl like you get all the brains. I just get to say tahnks for he answer.
2011年12月25日 12:11
Now that’s sbutle! Great to hear from you.
2012年01月30日 00:12
I had no idea how to aproapch this before-now I’m locked and loaded.
2012年02月01日 14:55
That’s 2 celevr by half and 2×2 clever 4 me. Thanks!
2011年12月27日 15:57
Do you have more great articels like this one?
2012年01月30日 16:03
Gosh, I wish I would have had that information elaerir!
2012年02月01日 17:53
An answer from an epexrt! Thanks for contributing.