跟老齐学Python之dict()的操作方法

2019-10-05 19:24:44刘景俊

删除键值对的方法有两个,但是两者有一点区别

>>>#d.pop(key),根据key删除相应的键值对,并返回该值
>>> new_web.pop('second')
'baidu'

>>> del new_web[3]   #没有返回值,如果删除键不存在,返回错误
>>> new_web
{1: 'google', 'twitter': 4}
>>> del new_web[9]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 9

用d.update(d2)可以把d2合并到d中。

>>> cnweb
{'qq': 'first in cn', 'python': 'qiwsir.github.io', 'alibaba': 'Business'}
>>> website
{1: 'google', 'second': 'baidu', 3: 'facebook', 'twitter': 4}

>>> website.update(cnweb)  #把cnweb合并到website内
>>> website         #变化了
{'qq': 'first in cn', 1: 'google', 'second': 'baidu', 3: 'facebook', 'python': 'qiwsir.github.io', 'twitter': 4, 'alibaba': 'Business'}
>>> cnweb          #not changed
{'qq': 'first in cn', 'python': 'qiwsir.github.io', 'alibaba': 'Business'}

在本讲最后,要提醒看官,在python3中,dict有不少变化,比如能够进行字典解析,就类似列表解析那样,这可是非常有意思的东西哦。