侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python字典及字典基本操作方法详解

Python  /  管理员 发布于 7年前   397

本文实例讲述了Python字典及字典基本操作方法。分享给大家供大家参考,具体如下:

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一冉ǖ挠成淅嘈停镜牟僮靼ㄈ缦拢

(1)len():返回字典中键―值对的数量;
(2)d[k]:返回关键字对于的值;
(3)d[k]=v:将值关联到键值k上;
(4)del d[k]:删除键值为k的项;
(5)key in d:键值key是否在d中,是返回True,否则返回False。

一、字典的创建

1.1 直接创建字典

d={'one':1,'two':2,'three':3}print dprint d['two']print d['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}23>>>

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_items=[('one',1),('two',2),('three',3),('four',4)]print u'items中的内容:'print itemsprint u'利用dict创建字典,输出字典内容:'d=dict(items)print dprint u'查询字典中的内容:'print d['one']print d['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======items中的内容:[('one', 1), ('two', 2), ('three', 3), ('four', 4)]利用dict创建字典,输出字典内容:{'four': 4, 'three': 3, 'two': 2, 'one': 1}查询字典中的内容:13>>>

或者通过关键字创建字典

# _*_ coding:utf-8 _*_d=dict(one=1,two=2,three=3)print u'输出字典内容:'print dprint u'查询字典中的内容:'print d['one']print d['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======输出字典内容:{'three': 3, 'two': 2, 'one': 1}查询字典中的内容:13>>>

二、字典的格式化字符串

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dprint "three is %(three)s." %d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}three is 3.>>>

三、字典方法

3.1 clear函数:清除字典中的所有项

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3,'four':4}print dd.clear()print d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'four': 4, 'three': 3, 'two': 2, 'one': 1}{}>>>

请看下面两个例子

3.1.1

# _*_ coding:utf-8 _*_d={}dd=dd['one']=1d['two']=2print ddd={}print dprint dd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'two': 2, 'one': 1}{}{'two': 2, 'one': 1}>>>

3.1.2

# _*_ coding:utf-8 _*_d={}dd=dd['one']=1d['two']=2print ddd.clear()print dprint dd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'two': 2, 'one': 1}{}{}>>>

3.1.2与3.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。

3.2 copy函数:返回一个具有相同键值的新字典

# _*_ coding:utf-8 _*_x={'one':1,'two':2,'three':3,'test':['a','b','c']}print u'初始X字典:'print xprint u'X复制到Y:'y=x.copy()print u'Y字典:'print yy['three']=33print u'修改Y中的值,观察输出:'print yprint xprint u'删除Y中的值,观察输出'y['test'].remove('c')print yprint x

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======初始X字典:{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}X复制到Y:Y字典:{'test': ['a', 'b', 'c'], 'one': 1, 'three': 3, 'two': 2}修改Y中的值,观察输出:{'test': ['a', 'b', 'c'], 'one': 1, 'three': 33, 'two': 2}{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}删除Y中的值,观察输出{'test': ['a', 'b'], 'one': 1, 'three': 33, 'two': 2}{'test': ['a', 'b'], 'three': 3, 'two': 2, 'one': 1}>>>

注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。

# _*_ coding:utf-8 _*_from copy import deepcopyx={}x['test']=['a','b','c','d']y=x.copy()z=deepcopy(x)print u'输出:'print yprint zprint u'修改后输出:'x['test'].append('e')print yprint z

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======输出:{'test': ['a', 'b', 'c', 'd']}{'test': ['a', 'b', 'c', 'd']}修改后输出:{'test': ['a', 'b', 'c', 'd', 'e']}{'test': ['a', 'b', 'c', 'd']}>>>

3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

# _*_ coding:utf-8 _*_d=dict.fromkeys(['one','two','three'])print d

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': None, 'two': None, 'one': None}>>>

或者指定默认的对应值

# _*_ coding:utf-8 _*_d=dict.fromkeys(['one','two','three'],'unknow')print d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}>>>

3.4 get函数:访问字典成员

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.get('one')print d.get('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}1None>>>

注:get函数可以访问字典中不存在的键,当该键不存在是返回None

3.5 has_key函数:检查字典中是否含有给出的键

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.has_key('one')print d.has_key('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}TrueFalse>>>

3.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dlist=d.items()for key,value in list:  print key,':',value

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}three : 3two : 2one : 1>>>
# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dit=d.iteritems()for k,v in it:  print "d[%s]="%k,v

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}d[three]= 3d[two]= 2d[one]= 1>>>

3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint u'keys方法:'list=d.keys()print listprint u'\niterkeys方法:'it=d.iterkeys()for x in it:  print x

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}keys方法:['three', 'two', 'one']iterkeys方法:threetwoone>>>

3.8 pop函数:删除字典中对应的键

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dd.pop('one')print d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}{'three': 3, 'two': 2}>>>

3.9 popitem函数:移出字典中的项

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dd.popitem()print d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 1}{'two': 2, 'one': 1}>>>

3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

# _*_ coding:utf-8 _*_d={'one':1,'two':2,'three':3}print dprint d.setdefault('one',1)print d.setdefault('four',4)print d

运算结果:

{'three': 3, 'two': 2, 'one': 1}14{'four': 4, 'three': 3, 'two': 2, 'one': 1}>>>

3.11 update函数:用一个字典更新另外一个字典

# _*_ coding:utf-8 _*_d={  'one':123,  'two':2,  'three':3  }print dx={'one':1}d.update(x)print d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py======={'three': 3, 'two': 2, 'one': 123}{'three': 3, 'two': 2, 'one': 1}>>>

3.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

# _*_ coding:utf-8 _*_d={  'one':123,  'two':2,  'three':3,  'test':2  }print d.values()

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======[2, 3, 2, 123]>>>

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字典操作技巧汇总》、《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    python使用Tkinter实现在线音乐播放器
    下一条:
    Python操作MySQL数据库的三种方法总结
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客