首页 > 编程 > Python > 正文

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

2020-02-22 23:03:56
字体:
来源:转载
供稿:网友

本文实例讲述了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}>>>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表