标签:
字典是python语言中唯一的映射类型。
映射类型对象里哈希值(key,键)和指向的对象(value,值)是一对多的关系,通常被认为是可变的哈希表。
字典的对象是可变的,它是一个容器类型,能存储任意个数的python对象,其中也可包括其他容器类型。
字典中的数据是无序排列的。
字典中键与值用“:”分开、项与项之间用“,”分开、字典中值必须是唯一的,而值可以不唯一!
1.创建dict
简单的说字典就是用大括号“{}”括起来的键值对的集合。
一般形式:
>>> adict={‘name‘:‘fly‘,‘age‘:30,‘sex‘:‘man‘}
>>> bdict={}
>>> type(bdict)
<type ‘dict‘>
>>> type(adict)
<type ‘dict‘>>>>
使用dict()函数:
>>> cdict = dict()2、dict的增删改查
>>> type(cdict)
<type ‘dict‘>
>>> cdict
{}
>>> ddict = dict(([‘a‘,1],[‘b‘,2]))
>>> ddict
{‘a‘: 1, ‘b‘: 2}
>>> edict = dict(name=‘flyer‘,sex=‘man‘)
>>> edict
{‘name‘: ‘flyer‘, ‘sex‘: ‘man‘}
>>>
>>> adict = {‘age‘: 30, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
增
adict[new_key] = value
>>> adict[‘telphone‘]= 1888888888
>>> adict
{‘age‘: 30, ‘telphone‘: 1888888888, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
删
>>> del adict[‘age‘]
>>> adict
{‘telphone‘: 1888888888, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> adict
{‘telphone‘: 1888888888, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> adict.pop(‘telphone‘)
1888888888
>>> del adict #删除整个字典
如果删除的元素不存在
>>> adict = {‘age‘: 30, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> del adict[‘wife‘]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ‘wife‘
>>> adict.pop(‘wife‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ‘wife‘
>>>
改
adict[old_key] = new_value
>>> adict
{‘age‘: 30, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> adict[‘name‘]=‘fhr‘
>>> adict
{‘age‘: 30, ‘name‘: ‘fhr‘, ‘sex‘: ‘man‘}
>>>
查
>>> adict
{‘age‘: 30, ‘name‘: ‘fhr‘, ‘sex‘: ‘man‘}
>>> adict.has_key(‘name‘)
True
>>> adict.has_key(‘wife‘)
False
>>> ‘name‘ in adict
True
>>> ‘wife‘ in adict
False
>>>
>>> adict.get(‘age‘)3.映射类型操作符
30
>>> adict.get(‘wife‘)
>>> print adict.get(‘wife‘)
None
>>> adict[‘age‘]
30
>>> adict[‘wife‘]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ‘wife‘>>>
标准类型操作符:+,-,*,/,<,>,<=,>=,==,!=,and,or,not
字典不支持拼接和重复操作符(+,*)
字典的比较
先比较字典的长度也就是字典元素个数,在比较键,然后比较值
>>> adict = {‘age‘: 30, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘,‘telphone‘:188888888}
>>> bdict = {‘age‘: 30, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> cdict = {‘age‘: 24, ‘name‘: ‘fly‘, ‘sex‘: ‘man‘}
>>> ddict = {‘age‘: 30, ‘name‘: ‘fly‘}
>>> edict = {‘age‘: 30, ‘name‘: ‘fly‘}
>>> cmp(adict,bdict)
1
>>> cmp(bdict,cdict)
1
>>> cmp(ddict,cdict)
-1
>>> cmp(ddict,edict)
0
>>>
4.字典的特性
字典的value可以是任何的python对象,key不行
1).字典中的键是唯一的,如果同一个key被赋值两次,后一个value会被记住
>>> dict = {‘name‘:‘fj‘,‘name‘:‘fhr‘}
>>> dict
{‘name‘: ‘fhr‘}
>>>
2).键必须是不可变的,可以用数,字符串或者元祖充当,但是列表不行。
>>> dict = {[‘name‘]:‘fjg‘,‘age‘:18}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: ‘list‘
5.字典的内置函数&方法
>>> adict = {‘age‘: 30, ‘name‘: ‘fhr‘, ‘sex‘: ‘man‘}
>>> adict.clear()
>>> adict
{}
标签:
原文地址:http://www.cnblogs.com/fujiangong/p/5132912.html