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


Posted in Python onJanuary 30, 2018

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

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

(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 d
print d['two']
print d['three']

运算结果:

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

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
print u'items中的内容:'
print items
print u'利用dict创建字典,输出字典内容:'
d=dict(items)
print d
print 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}
查询字典中的内容:
1
3
>>>

或者通过关键字创建字典

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

运算结果:

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

二、字典的格式化字符串

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
print "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 d
d.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=d
d['one']=1
d['two']=2
print dd
d={}
print d
print 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=d
d['one']=1
d['two']=2
print dd
d.clear()
print d
print 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 x
print u'X复制到Y:'
y=x.copy()
print u'Y字典:'
print y
y['three']=33
print u'修改Y中的值,观察输出:'
print y
print x
print u'删除Y中的值,观察输出'
y['test'].remove('c')
print y
print 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 deepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
print u'输出:'
print y
print z
print u'修改后输出:'
x['test'].append('e')
print y
print 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 d
print d.get('one')
print d.get('four')

运算结果:

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

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

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

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

运算结果:

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

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

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
list=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 : 3
two : 2
one : 1
>>>
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
it=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]= 3
d[two]= 2
d[one]= 1
>>>

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

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print u'keys方法:'
list=d.keys()
print list
print 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方法:
three
two
one
>>>

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

# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.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 d
d.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 d
print d.setdefault('one',1)
print d.setdefault('four',4)
print d

运算结果:

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

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

# _*_ coding:utf-8 _*_
d={
  'one':123,
  'two':2,
  'three':3
  }
print d
x={'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错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
Aug 22 Python
Python中关于使用模块的基础知识
May 24 Python
在Django的模型和公用函数中使用惰性翻译对象
Jul 27 Python
python类的继承实例详解
Mar 30 Python
python实现键盘控制鼠标移动
Nov 27 Python
Python基于datetime或time模块分别获取当前时间戳的方法实例
Feb 19 Python
python 的 scapy库,实现网卡收发包的例子
Jul 23 Python
使用python实现飞机大战游戏
Mar 23 Python
Python如何根据时间序列数据作图
May 12 Python
30行Python代码实现高分辨率图像导航的方法
May 22 Python
Pytorch如何切换 cpu和gpu的使用详解
Mar 01 Python
python中对列表的删除和添加方法详解
Feb 24 Python
Python操作MySQL数据库的三种方法总结
Jan 30 #Python
python3.5 tkinter实现页面跳转
Jan 30 #Python
python 连接各类主流数据库的实例代码
Jan 30 #Python
python操作oracle的完整教程分享
Jan 30 #Python
Python使用wxPython实现计算器
Jan 30 #Python
python链接oracle数据库以及数据库的增删改查实例
Jan 30 #Python
python实现简易版计算器
Jun 22 #Python
You might like
用PHP实现登陆验证码(类似条行码状)
2006/10/09 PHP
PHP $_SERVER详解
2009/01/16 PHP
PHP 分页原理分析,大家可以看看
2009/12/21 PHP
php实现以只读方式打开文件的方法
2015/03/16 PHP
CodeIgniter 完美解决URL含有中文字符串
2016/05/13 PHP
PHP编程实现微信企业向用户付款的方法示例
2017/07/26 PHP
windows下的WAMP环境搭建图文教程(推荐)
2017/07/27 PHP
php实现支付宝当面付(扫码支付)功能
2018/05/30 PHP
解决php写入数据库乱码的问题
2019/09/17 PHP
返回对象在当前级别中是第几个元素的实现代码
2011/01/20 Javascript
node.js使用require()函数加载模块
2014/11/26 Javascript
node.js中的fs.readSync方法使用说明
2014/12/17 Javascript
jQuery中attr()与prop()函数用法实例详解(附用法区别)
2015/12/29 Javascript
JS面试题---关于算法台阶的问题
2016/07/26 Javascript
Javascript中常用类型的格式化方法小结
2016/12/26 Javascript
基于es6三点运算符的使用方法(实例讲解)
2017/10/12 Javascript
深入理解JS异步编程-Promise
2019/06/03 Javascript
微信小程序可滑动月日历组件使用详解
2019/10/21 Javascript
[03:07]【DOTA2亚洲邀请赛】我们,梦开始的地方
2017/03/07 DOTA
零基础写python爬虫之抓取百度贴吧并存储到本地txt文件改进版
2014/11/06 Python
详解Python中的Cookie模块使用
2015/07/06 Python
Python 基础之字符串string详解及实例
2017/04/01 Python
python2.7实现邮件发送功能
2018/12/12 Python
selenium python 实现基本自动化测试的示例代码
2019/02/25 Python
sklearn+python:线性回归案例
2020/02/24 Python
英国香水店:The Perfume Shop
2017/03/27 全球购物
英国优质家居用品网上品牌:URBANARA
2018/06/01 全球购物
Lookfantastic意大利官网:英国知名美妆购物网站
2019/05/31 全球购物
俄罗斯商务邀请函
2014/01/26 职场文书
技术总监管理职责范本
2014/03/06 职场文书
村长贪污检举信
2014/04/04 职场文书
中学生期中自我鉴定
2014/04/20 职场文书
2016年教师节感恩寄语
2015/12/04 职场文书
社区服务理念口号
2015/12/25 职场文书
Python爬虫爬取全球疫情数据并存储到mysql数据库的步骤
2021/03/29 Python
使用Nginx+Tomcat实现负载均衡的全过程
2022/05/30 Servers