Python学习之字典的基本操作及字典中的函数

19 篇文章 0 订阅
17 篇文章 1 订阅

在上一篇Python学习之字典当中,学习了Python一种独特的数据对象类型,字典以及如何创建字典和创建字典的方法。
这一篇主要学习字典的基本操作及字典中的函数。对于字典的基本操作。

获取字典的长度
使用内置函数len(dict)

>>> test = {"a":"1","b":"3","c":"4"}
>>> test
{'a': '1', 'c': '4', 'b': '3'}
>>> len(test)
3

通过键来查找字典中的值

>>> print test
{'a': '1', 'c': '4', 'b': '3', 'd': '5'}
>>> test['d']
'5'
>>> test['3']     #如果字典中不存在键,那么就会报错

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    test['3']
KeyError: '3'
>>> test['a']
'1'
>>> 

向字典中增加键值对

>>> print test
{'a': '1', 'c': '4', 'b': '3', 'd': '5'}
>>> test["e"] = "6"
>>> test
{'a': '1', 'c': '4', 'b': '3', 'e': '6', 'd': '5'}
>>> 

从字典中删除一个键值对

>>> print test
{'a': '1', 'c': '4', 'b': '3', 'e': '6', 'd': '5'}
>>> del test['a']
>>> print test
{'c': '4', 'b': '3', 'e': '6', 'd': '5'}
>>> 

判断某个键是否存在于字典中
关键代码 key in dict,如果存在则返回true,如果不存在,则返回false

>>> print test
{'c': '4', 'b': '3', 'e': '6', 'd': '5'}
>>> 'c' in test
True
>>> 'a' in test
False
>>> 'f' in test
False
>>> 

字典中字符串的格式化输出

>>> print test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> print "the web\'s name is %(name)s ,the web\'s website is %(website)s."%test
the web's name is baidu ,the web's website is https://www.baidu.com.
>>> 

从以上代码中,我们可以看到,字符串中如果调用字典中的key,使用%( )s,然后在结尾使用% dict从字典中检索key。
不过字典中的字符串的格式化输出不怎么实用。
下面我们写一个网页代码来小试牛刀一下

>>> code = "<html><head><title>%(string)s</title><body><p>This is the %(page)s</p></body></head></html>"
>>> testdict = {"string":"test page","page":"test page"}
>>>> code % testdict
'<html><head><title>test page</title><body><p>This is the test page</p></body></head></html>'
>>> 

其实这个例子并没有什么实际意义,但是很好玩儿呀!

接着上面的,从这里开始,开始学习字典中的函数
和前面所讲述的其他对象一样,字典中也有一些函数,通过这些函数,可以实现对字典的操作。

1、copy和deepcopy
通常,copy就是简单的理解为将原来的东西复制一份,但是如果以为copy的含义仅仅是这个,那么孩子,涉世未深,还得探索呀。在Python中,或者说其他的编程语言中,copy可不仅仅是那么简单的。

>>> a = 1
>>> b = a
>>> b
1

上面的代码中,我们可以看到,我们似乎是得到了两个1,但是真的是这样吗?我们知道,在Python中,对象有类型,变量无类型。所以,我们可以看得出,变量只是一个标签而已,相当于爸爸有1块钱,然后爸爸把1块钱给了孩子,那么孩子得到的依然使这1块钱,1块钱的实质是不变得。粗糙理解一下啊。我也是新手,不知道例子举得恰不恰当。不信,我们可以通过id( )来验证。

>>> a = 1
>>> b = a
>>> b
1
>>> id(a)
10728248
>>> id(b)
10728248
>>> 

在其它的数据类型中,也是同样,这里只实验一下字典类型

>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> demo = test
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> id(test)
11179680
>>> id(demo)
11179680
>>> 

我们可以看到又是一个对象贴了两个标签,这是用赋值的方式实现对象的所谓的“假装拷贝”。那么如果是copy的方法呢

>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> demo = test.copy()
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> id(test)
11179680
>>> id(demo)
11349728
>>> 

我们发现,这次得到的demo和原来的demo是不同的,它在内存中另开辟了一个空间。如果我尝试修改demo,那么对于原来的test应该不会造成影响,实验的结果会不会是如我所说的呢?

>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> demo = test.copy()
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> id(test)
11179680
>>> id(demo)
11349728
>>> demo ["name1"] = "google"
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu', 'name1': 'google'}
>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> 

如果不用copy,直接用赋值的方式改变结果呢?

>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> demo = test
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu'}
>>> demo ["name1"] = "google"
>>> demo
{'website': 'https://www.baidu.com', 'name': 'baidu', 'name1': 'google'}
>>> test
{'website': 'https://www.baidu.com', 'name': 'baidu', 'name1': 'google'}
>>> id(test)
11179680
>>> id(demo)
11179680
>>> 

我们发现如果修改了demo对象的值,那么test对象的值也跟着改变了
前方高能预警,然而事情并非想象的那么简单,为甚呢?我也不解,慢慢来看吧!

>>> test = {"name":"website","web":["baidu","google","360"]}
>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> demo = test.copy()
>>> demo
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> id(test)
11349728
>>> id(demo)
11351568
>>> 

通过实验发现,testdemo在内存中是两个不同的对象

>>> demo['web'].remove('360')
>>> demo
{'web': ['baidu', 'google'], 'name': 'website'}
>>> test
{'web': ['baidu', 'google'], 'name': 'website'}
>>> 

上面的代码中,我们尝试将字典中的web对应的列表中的360移除,按照我们之前的推测,demo和test在内存中是属于两个不同的对象,但是,我们发现,当我们移除demo中的360后,test中web对应的列表也跟着变化了。是不是开始晕圈圈了呢。
解释:在demo所对应字典的对象中,键‘web’对应的值是一个列表,为[‘baidu’, ‘google’, ‘360’],当用remove移除列表中的一个元素360后,变为[‘baidu’, ‘google’]
毋庸置疑,前面所说的原理是有效的,但是为什么当值是列表的时候就不奏效了呢?
为了解决这个迷惑,我们还得用id( )来破解,我为什么要说破解呢,我又不是一个hacker。

>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> demo = test.copy()
>>> demo
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> id(test)
11349728
>>> id(demo)
11351568
>>> demo['web'].remove('360')
>>> demo
{'web': ['baidu', 'google'], 'name': 'website'}
>>> test
{'web': ['baidu', 'google'], 'name': 'website'}
>>> id(demo)
11351568
>>> id(test)
11349728
>>> 

testdemo对应着两个不同的对象,确实这样,但是这个对象(字典)是由两个键值对组成的,其中一个键的值是列表。

>>> test = {"name":"website","web":["baidu","google","360"]}
>>> demo = test.copy()
>>> id(test['web'])
140262388822528
>>> id(demo['web'])
140262388822528
>>> 

注意:我们发现了这样一个事实,列表是同一个对象,但是,作为字符串为值得键值对应的是分属不同的对象。

>>> test = {"name":"website","web":["baidu","google","360"]}
>>> demo = test.copy()
>>> id(test["web"])
140262388728536
>>> id(demo["web"])
140262388728536
>>> id(test["name"])
140262388812848
>>> id(demo["name"])
140262388812848
>>> demo['web'].remove('360')
>>> demo
{'web': ['baidu', 'google'], 'name': 'website'}
>>> test
{'web': ['baidu', 'google'], 'name': 'website'}
>>> id(test['name'])
140262388812848
>>> id(demo['name'])
140262388812848
>>> demo['name']="website1"       #改变name的值,下面的id就看到了
>>> demo
{'web': ['baidu', 'google'], 'name': 'website1'}
>>> test
{'web': ['baidu', 'google'], 'name': 'website'}
>>> id(test['web'])
140262388728536
>>> id(demo['web'])
140262388728536
>>> id(demo['name'])
140262388826688
>>> id(test['name'])
140262388812848
>>> 

这个事实说明了为什么修改一个列表,另外一个列表也跟随的原因了;而修改一个字符串,另外一个字符串不跟随着修改的原因了。
那么问题来了,我们想要在改被复制中的字典中,修改字典中的key所对应的value的值,怎么办?
所以copy我们称为浅拷贝
所谓浅拷贝意思就是,Pyhon中的存储的对象类型为基本数据类型和,复杂数据类型,如果是基本数据类型,比如是int,str等,那么在被复制的字典中,就会重新存储,但是,如果是复杂的列表的对象类型,那么Python使用copy就对被复制对象的数据进行引用。所以如果对象太复杂了,那么还是别费劲了,引用一下就可以了。
所以Python引入了深拷贝deep copy,但是,要通过import copy导入一个模块

>>> import copy
>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> demo = copy.deepcopy(test)
>>> demo
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> id(test["name"])
140262388812848
>>> id(demo["name"])
140262388812848
>>> id(test['web'])
140262388822600
>>> id(demo['web'])
140262388822888
>>> 

发现,对于列表不再是简单的引用了。

>>> import copy
>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> demo = copy.deepcopy(test)
>>> demo
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> id(test["name"])
140262388812848
>>> id(demo["name"])
140262388812848
>>> id(test['web'])
140262388822600
>>> id(demo['web'])
140262388822888
>>> demo['web'].remove('360')
>>> demo
{'web': ['baidu', 'google'], 'name': 'website'}
>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> 

果然不再跟随着改变了,哈哈,试一试才过瘾
试一下append(),大声的告诉我,你已经忘了。

>>> demo['web'].append('sina')
>>> demo
{'web': ['baidu', 'google', 'sina'], 'name': 'website'}
>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> 

使用clear

>>>help(dict.clear)
help on method_descriptor:

clear(...)
    D.clear() -> None.  Remove all items from D.
(END) 

dict.clear()意思是指将字典中的所有元素都清空。使字典成为一个空字典
而之前我们接触过del dict这个是指将字典从内存中删除,不存在了。
上代码,我也不喜欢婆婆妈妈,长篇大论

>>> a = {'a':1,'b':2}
>>> a
{'a': 1, 'b': 2}
>>> a.clear()
>>> a
{}
>>> b = {'a':1,'b':2}
>>> del b
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> 

函数之get和setdefault
get()和之前的dict[ ]是由区别的,
get()中如果指定的Key不存在,则返回None,但是dict[ ]就会报错
上代码

>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> print test.get('web')
['baidu', 'google', '360']
>>> print test.get('haha')     #返回None
None
>>> test['web']
['baidu', 'google', '360']
>>> test['haha']              #报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'haha'
>>> 

注意,但是get还有一种用法,我们使用帮助

>>>help(dict.get)
>get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
(END) 

意思就是如果键对应的值不存在则返回可选参数d,默认为None

>>> print test.get('haha','python')
python
>>> 

setdefault( )函数

help(dict.setdefault)
Help on method_descriptor:

setdefault(…)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
(END)
解释:如果key存在,则返回value,如果不存在,则返回None,并将其添加到字典中,如果不存在,在后面指定可选参数,则将不存在的Key和value添加到字典中。
以下代码中可以解释这一含义。

>>> test
{'web': ['baidu', 'google', '360'], 'name': 'website'}
>>> print test.setdefault('web')
['baidu', 'google', '360']
>>> print test.setdefault('haha')
None
>>> print test
{'web': ['baidu', 'google', '360'], 'haha': None, 'name': 'website'}
>>> print test.setdefault('code','python')
python
>>> print test
{'web': ['baidu', 'google', '360'], 'code': 'python', 'haha': None, 'name': 'website'}
>>> 

除了以上字典中的函数,在字典中,还有’
items/iteritems,keys/iterkeys,values/itervalues函数
这三组函数有相似的地方,所以在这里只实验第一种函数,相信另外两种函数只要同学们一看就会懂。

help(dict.items)
Help on method_descriptor:

items(…)
D.items() -> list of D’s (key, value) pairs, as 2-tuples
(END)
解释,列出字典中的键值对,列表中的元素是由Keyvalue组成的一个元组
代码:

>>> test
{'web': ['baidu', 'google', '360'], 'code': 'python', 'haha': None, 'name': 'website'}
>>> test.items()
[('web', ['baidu', 'google', '360']), ('code', 'python'), ('haha', None), ('name', 'website')]
>>> 

itertems( )函数

help(dict.iteritems)
Help on method_descriptor:

iteritems(…)
D.iteritems() -> an iterator over the (key, value) items of D
(END)
先看代码

>>> test
{'web': ['baidu', 'google', '360'], 'code': 'python', 'haha': None, 'name': 'website'}
>>> test.iteritems()
<dictionary-itemiterator object at 0x7f9161dcff70>
>>> type(test.iteritems())
<type 'dictionary-itemiterator'>
>>> list(test.iteritems())
[('web', ['baidu', 'google', '360']), ('code', 'python'), ('haha', None), ('name', 'website')]
>>> 

我们可以看到,如果直接使用dict.iteritems( ),那么我们将会得到一个dictionary-itemiterator类型,不过这种迭代器类型的数据不能直接输出,必须要使用List( )转换才能输出。
另外的两种函数也同这个类似。
pop和popitem函数
不知道你是否记得在学习列表的时候,删除列表中的元素的函数是哪一个吗?悄悄告诉我,你是不是忘了。哈哈
没错,就是pop和remove,这两个的区别在于
list.remove(x)用来删除指定的元素,而list.pop([x])用于删除指定索引的元素,如果不提供索引值,就会默认删除最后一个

help(dict.pop)
Help on method_descriptor:

pop(…)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
(END)
解释:删除指定键的键值对,如果Key没有被发现,则返回可选给定的可选参数,否则,则会引发KeyError错误。
还是看代码吧:

>>> test
{'web': ['baidu', 'google', '360'], 'code': 'python', 'haha': None, 'name': 'website'}
>>> test.pop('code')
'python'
>>> test
{'web': ['baidu', 'google', '360'], 'haha': None, 'name': 'website'}
>>> test.pop('code')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'code'
>>> test.pop('code','python')
'python'
>>> test
{'web': ['baidu', 'google', '360'], 'haha': None, 'name': 'website'}
>>> 

popitem( )函数和List.pop()相似,可以不用写参数,但是注意,popitem()是随机删除,而list.pop()是删除最后一个
代码呈上:

>>> test
{'web': ['baidu', 'google', '360'], 'haha': None, 'name': 'website'}
>>> demo.popitem()
('web', ['baidu', 'google', 'sina'])
>>> demo.popitem()
('name', 'website')
>>> 

注意,如果字典中没有值得话,当使用popitem的时候,就会提示字典已经为空了,没有可以要删除的东西了。
update函数
顾名思义,更新字典中的值

help(dict.update)
Help on method_descriptor:

update(…)
D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
(END)

>>> up = {"test":"this is test"}
>>> down = {"yes":"you are right"}
>>> up.update(down)
>>> up
{'test': 'this is test', 'yes': 'you are right'}
>>> down.update([("code","python"),("code1","java")])
>>> down
{'code1': 'java', 'yes': 'you are right', 'code': 'python'}
>>> 

hash_key函数

help(dict.has_key)
Help on method_descriptor:

has_key(…)
D.has_key(k) -> True if D has a key k, else False
(END)

解释:这个函数的功能是判断字典中是否存在某个键
如果存在,则返回true,否则返回false
本节学习的最后一个函数了,以代码的方式结束

>>> test
{'web': ['baidu', 'google', '360'], 'haha': None, 'name': 'website'}
>>> test.has_key('web')
True
>>> test.has_key('code')
False
>>> 

好了,以上就是对于字典的基本操作和字典中的函数的操作,都是常见的操作和函数。当然,字典中的函数不仅仅是这些,慢慢来,以后还多的是呢。
明天更新集合。
晚安!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值