您的位置:首页 > 编程语言 > Python开发

【Python之旅】第二篇(四):字典

2015-09-11 22:01 549 查看

说明:

    显然Python中字典的学习过程与列表是一样的,主要是围绕下面的函数来进行重点学习:

'computer'
[p]

>>> xpleaf['girlfriend'] = 'none' >>> xpleaf {'girlfriend': 'none', 'hobby': 'IT', 'dream': 'excellent hacker', 'name': 'xpleaf', 'occupation': 'student'}[p]>>> xpleaf.items() [('girlfriend', 'none'), ('hobby', 'IT'), ('dream', 'excellent hacker'), ('name', 'xpleaf'), ('occupation', 'student')][p]>>> for key in xpleaf: ...   print key,xpleaf[key] ...  girlfriend none hobby IT dream excellent hacker name xpleaf occupation student[p]>>> xpleaf.keys() ['girlfriend', 'hobby', 'dream', 'name', 'occupation'][p]>>> a {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 6: 'f'} >>> a.popitem() ('a', 1) >>> a.popitem() ('c', 3) >>> a.popitem() ('b', 2) >>> a.popitem() ('e', 5) >>> a.popitem() ('d', 4) >>> a.popitem() (6, 'f')[p]>>> a {'a': 1, 'c': 3, 'b': 2} >>> b {'e': 4, 'g': 6, 'f': 5} >>> a.update(b) >>> a {'a': 1, 'c': 3, 'b': 2, 'e': 4, 'g': 6, 'f': 5} >>> b {'e': 4, 'g': 6, 'f': 5}[p]>>> xpleaf {'name': 'xpleaf', 'weight': '55kg', 'wife': None, 'hobby': 'IT', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf.values() ['xpleaf', '55kg', None, 'IT', 'excellent hacker', 'student'][p]>>> del a >>> a Traceback (most recent call last):   File "<stdin>][p]


[strong]11.copy()函数


·功能:对字典进行浅复制;


·Python中普通情况下的“复制”:>>> xpleaf {'name': 'xpleaf', 'weight': '55kg', 'wife': None, 'hobby': 'IT', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf_copy = xpleaf >>> xpleaf_copy {'name': 'xpleaf', 'weight': '55kg', 'wife': None, 'hobby': 'IT', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf['hobby'] = 'IT_Field' >>> xpleaf_copy {'name': 'xpleaf', 'weight': '55kg', 'wife': None, 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf_copy['wife'] = 'None!!!' >>> xpleaf_copy {'name': 'xpleaf', 'weight': '55kg', 'wife': 'None!!!', 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf {'name': 'xpleaf', 'weight': '55kg', 'wife': 'None!!!', 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'}·即将变量赋给其它变量只是将对象(实际的字典)作一个引用传递而已,修改任何一个引用都会改变原来对象的值;

·copy()的浅复制功能则不是引用传递:>>> xpleaf_copy2 = xpleaf.copy() >>> xpleaf_copy2 {'name': 'xpleaf', 'weight': '55kg', 'wife': 'None!!!', 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf_copy2['wife'] = 'CL' >>> xpleaf_copy2 {'name': 'xpleaf', 'weight': '55kg', 'wife': 'CL', 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'} >>> xpleaf {'name': 'xpleaf', 'weight': '55kg', 'wife': 'None!!!', 'hobby': 'IT_Field', 'dream': 'excellent hacker', 'occupation': 'student'}·当然copy()更重要的作用不仅在于此,这里只是简单提及它的作用。



阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: