字典的操作

Posted AllenZhang_(*^▽^*)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典的操作相关的知识,希望对你有一定的参考价值。

删除

del

>>> people = {kind: beauty, age: 22}
>>> del people[age]
>>> people
{kind: beauty}

pop

>>> people = {kind: beauty, age: 22}
>>> people.pop(age)
22
>>> people
{kind: beauty}

popitem 删除一个,不带参数(字典是无序的,不确定会删除哪个)

>>> people = {kind: beauty, age: 22}
>>> people.popitem()
(kind, beauty)
>>> people
{age: 22}

增、改

setdefault 如果不存指定键在就新增,存在不做任何操作

>>> people = {kind: beauty, age: 22}
>>> people.setdefault(like, sport)
sport
>>> people
{kind: beauty, like: sport, age: 22}
>>> people.setdefault(kind, fool)
beauty
>>> people
{kind: beauty, like: sport, age: 22}

update 很常用,直接修改或新增

get  没取到为None(也可设置为其它)

>>> people = {kind: beauty, age: 22}
>>> like = people.get(like)
>>> like
>>> print like
None

in 是否存在该键(Python2里还有has_key也是相同用法,Python3里没有has_key)

>>> people = {kind: beauty, age: 22}
>>> print kind in people
True
>>> people = {kind: beauty, age: 22}
>>> print(agein people)
True

其它操作

items 转换为字典

>>> people
{kind: beauty, like: sport, age: 22}
>>> people.items()
dict_items([(kind, beauty), (like, sport), (age, 22)])

fromkeys 创建字典,所有的键共用一个值(修改一个,其它的都变,像浅copy)

>>> like = dict.fromkeys([sport, singing, dance], 666)
>>> like
{singing: 666, sport: 666, dance: 666}
>>> like[singing] = yes
>>> like
{singing: yes, sport: 666, dance: 666}

>>> lau = dict.fromkeys([C, Java, Python], [code, yes])
>>> lau
{C: [code, yes], Python: [code, yes], Java: [code, yes]}
>>> lau[Python][1] = no
>>> lau
{C: [code, no], Python: [code, no], Java: [code, no]}

 

以上是关于字典的操作的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

VSCode自定义代码片段——git命令操作一个完整流程

VSCode自定义代码片段15——git命令操作一个完整流程

VSCode自定义代码片段15——git命令操作一个完整流程