Python学习心得(二) 字典Dictionary
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python学习心得(二) 字典Dictionary,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1909字,纯文字阅读大概需要3分钟。
内容图文
![Python学习心得(二) 字典Dictionary](/upload/InfoBanner/zyjiaocheng/1113/dc98272aa4284560a7367af55e2e4eca.jpg)
前言 . 在Python中字典就是一系列的键值对,一种可变容器,可以存储任意对象,也被称作关联数组或哈希表。
1.基本语法
用一对花括号{}中的一系列键值对表示,键与值之间用冒号分隔,键值对之间用逗号分隔,例如:
blogger = {‘name‘: ‘binguo‘,‘age‘: 27}
2.访问字典中的值
print ‘name:‘+ blogger[‘name‘] +‘ age:‘ +str(blogger[‘age‘])
3.添加键值对
blogger[‘gender‘] = ‘male‘ print blogger #{‘gender‘: ‘male‘, ‘age‘: 27, ‘name‘: ‘binguo‘}
4.修改字典中的值
blogger[‘name‘] = ‘binguo168‘ print blogger[‘name‘] #binguo168
5.删除键值对
del blogger[‘age‘] print blogger #{‘gender‘: ‘male‘, ‘name‘: ‘binguo168‘}
6.遍历所有的键值对
for key,value in blogger.items(): print ‘\nkey:‘+key print ‘value:‘+value ‘‘‘ key:gender value:male key:name value:binguo168 ‘‘‘
7.遍历字典中所有的键
for key in blogger.keys(): print ‘key:‘+key """ key:gender key:name """
#按顺序遍历字典中所有的键 for key in sorted(blogger.keys()): #对blogger.keys()方法调用了 临时性排序函数sorted() print ‘key:‘+key
8.遍历字典中所有的值
for value in blogger.values(): print ‘value:‘+value """ value:male value:binguo168 """ #当字典中含有重复元素时,可以集合(set)予以处理,比如: blogger[‘NameUsedBefore‘] = ‘binguo168‘ #此时blogger字典的value值中就出现了重复元素:[‘male‘, ‘binguo168‘, ‘binguo168‘] print blogger.values() #通过转换集合的方式,剔除了重复元素 for newvalue in set(blogger.values()): print newvalue """ binguo168 male """
9.嵌套(列表中嵌套字典、字典中嵌套列表、字典中嵌套字典)
blogger2 = [{‘name‘:‘bingru‘,‘age‘:26},{‘company‘:‘csdn‘,‘salary‘:‘you guess‘}] for message in blogger2: print message #字典嵌套列表 blogger3 ={‘personmessage‘:[‘binguo‘,‘male‘,‘27‘],‘hobby‘:‘study‘} for key3,value3 in blogger3.items(): print ‘\nkey3:‘ + key3 print value3 #字典嵌套字典 bloggers = {‘binguo‘:{‘gender‘:‘male‘,‘age‘:27}, ‘binguo168‘:{‘hobby‘:‘study‘,‘education‘:‘graduate from primary school‘} } for blogger,blogger_info in bloggers.items(): print ‘\nblogger:‘ + blogger print blogger_info """ blogger:binguo168 {‘hobby‘: ‘study‘, ‘education‘: ‘graduate from primary school‘} blogger:binguo {‘gender‘: ‘male‘, ‘age‘: 27} """
参考资料 《Python编程从入门到实践》
原文:http://www.cnblogs.com/binguo2008/p/7215512.html
内容总结
以上是互联网集市为您收集整理的Python学习心得(二) 字典Dictionary全部内容,希望文章能够帮你解决Python学习心得(二) 字典Dictionary所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。