cheng029 发表于 2016-3-7 08:56:14

Python 字典的特点和常用操作

一、字典帮助文档


1
2
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']





二、字典的特点
1、字典是无序的,它不能通过偏移来存取,只能通过键来存取。可以嵌套,字典 = {'key':value} key:类似我们现实的钥匙,而value则是锁。一个钥匙开一个锁

1
2
3
4
5
>>> info={'a':1,'b':2}
>>> info
{'a': 1, 'b': 2}
>>> info['a']
1





2、字典内部没有顺序,通过键来读取内容,可嵌套,方便我们组织多种数据结构,并且可以原地修改里面的内容,属于可变类型。


1
2
3
4
5
6
>>> binfo = {'a':,'b':}
>>> binfo
{'a': , 'b': }
>>> binfo['a']=5
>>> binfo
{'a': , 'b': }





3、组成字典的键必须是不可变的数据类型,比如,数字,字符串,元组等,列表等可变对象不能作为键.

1
2
3
4
5
6
7
8
9
>>> binfo={1:'22',2:'dd'}
>>> binfo
{1: '22', 2: 'dd'}
>>> cinfo={'22':'222','aa':11}
>>> cinfo
{'aa': 11, '22': '222'}
>>> dinfo={(1,2,3):'ss',('b','c'):'222'}
>>> dinfo
{('b', 'c'): '222', (1, 2, 3): 'ss'}





元组里面的元素必须也是不可以改变的

1
2
3
4
>>> dinfo={(1,2,):'ss',('b','c'):'222'}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable






三、字典的常用操作

1、创建字典。{},dict()

1
2
3
4
5
6
info = {'name':'lilei', 'age': 20}
>>> info
{'age': 20, 'name': 'lilei'}
info= dict(name='lilei',age=20)
>>> info
{'age': 20, 'name': 'lilei'}





2、添加内容 a['xx'] = 'xx' ,key不存在,即为添加

1
2
3
info['phone'] = 'iphone5'
>>> info
{'phone': 'iphone5', 'age': 20, 'name': 'lilei'





3、修改内容 a['xx'] = 'xx' ,key存在,即为修改

1
2
3
info['phone'] = 'htc'
>>> info
{'phone': 'htc', 'age': 20, 'name': 'lilei'}






update 参数是一个字典的类型,会覆盖相同键的值

1
2
3
info.update({'city':'beijing','phone':'nokia'})
>>> info
{'phone': 'nokia', 'age': 20, 'name': 'lilei', 'city': 'beijing'} #htc 变成了nokia了







4、删除 del,clear,pop

del info['phone']#删除某个元素

1
2
3
4
5
6
7
>>> info = {'name':'lilei', 'age': 20}
>>> info.update({'city':'beijing','phone':'nokia'})
>>> info
{'city': 'beijing', 'age': 20, 'name': 'lilei', 'phone': 'nokia'}
>>> del info['city']
>>> info
{'age': 20, 'name': 'lilei', 'phone': 'nokia'}






1
2
3
4
>>> del info['city']#删除已经不存在的key,会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'city'






info.clear()删除字典的全部元素

1
2
3
>>> info.clear()
>>> info
{}





pop 删除指定的key

1
2
3
>>> info = {'name':'lilei', 'age': 20}
>>> info
{'age': 20, 'name': 'lilei'}







1
2
3
4
>>> info.pop('name') #删除key为name的元素,并返回key对应的value
'lilei'
>>> info
{'age': 20}






1
2
3
4
>>> info.pop('name')#删除已经不存在的key,会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'








1
2
3
4
>>> info.pop('name','defalutValue') #key不存在,返回指定的值'defalutValue'
'defalutValue'
>>> info
{'age': 20}






5、字典的pop方法和list的pop方法的区别,字典的pop删除不存在的key时,可以指定默认值

1
2
3
4
5
6
7
8
9
10
11
>>> l=
>>> l.pop() #不指定参数,就是pop最后一个元素
4
>>> l

>>> l.pop(2) #可以具体指定删除哪个元素
3
>>> l.pop(2) #下标不存在的元素会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range







6、in 和 has_key() 成员关系操作

1
2
3
4
5
6
7
>>> info = {'name':'lilei', 'age': 20}
>>> info
{'age': 20, 'name': 'lilei'}
>>> 'name' in info
True
>>> info.has_key('name')
True







7、keys(): 返回的是列表,里面包含了字典的所有键
values():返回的是列表,里面包含了字典的所有值
items:生成一个字典的容器:[()]

1
2
3
4
5
6
7
>>> info = {'name':'lilei', 'age': 20}
>>> key=info.keys()
>>> key
['age', 'name']
>>> values=info.values()
>>> values







1
2
>>> info.items()
[('age', 20), ('name', 'lilei')]







8、get:从字典中获得一个值

1
2
3
4
5
>>> info = {'name':'lilei', 'age': 20}
>>> info
{'age': 20, 'name': 'lilei'}
>>> info.get('name')
'lilei'





1
2
3
>>> b=info.get('age21') #如果是不存在的key,则返回NoneType
>>> type(b)
<type 'NoneType'>








1
2
>>> info.get('age2','22')#如果是不存在的key,可以指定返回一个默认值
'22'





练习:

已知字典:ainfo = {'ab':'liming','ac':20}

完成下面的操作

1 使用2个方法,输出的结果:
ainfo = {'ab':'liming','ac':20,'sex':'man','age':20}


>>> ainfo = {'ab':'liming','ac':20}
>>> ainfo['sex']='man'
>>> ainfo['age']=20
>>> ainfo
{'ac': 20, 'ab': 'liming', 'age': 20, 'sex': 'man'}


>>> ainfo.update({'sex':'man','age':20})
>>> ainfo
{'ac': 20, 'ab': 'liming', 'age': 20, 'sex': 'man'}


2 输出结果:['ab','ac']
>>> ainfo.keys()
['ac', 'ab']

3 输出结果:['liming',20]

4 通过2个方法返回键名ab对应的值。
5 通过2个方法删除键名ac对应的值。


页: [1]
查看完整版本: Python 字典的特点和常用操作