设为首页 收藏本站
查看: 855|回复: 0

[经验分享] Python 字典的特点和常用操作

[复制链接]

尚未签到

发表于 2016-3-7 08:56:14 | 显示全部楼层 |阅读模式
一、字典帮助文档

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':[1,2,3],'b':[4,5,6]}
>>> binfo
{'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> binfo['a'][2]=5
>>> binfo
{'a': [1, 2, 5], 'b': [4, 5, 6]}




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,[1,3]):'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=[1,2,3,4]
>>> l.pop() #不指定参数,就是pop最后一个元素
4
>>> l
[1, 2, 3]
>>> 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
[20, 'lilei']




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()[0:2]
['ac', 'ab']

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

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



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-187331-1-1.html 上篇帖子: python的简单介绍 下篇帖子: Python 元组和集合的特点及常用操作
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表