由键-值对构建的集合。

创建

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

dic1={}
type(dic1)

 

dic2=dict()
type(dic2)

 

Python基础——字典(dict) Python 第1张

初始化

dic2={'hello':123,'world':456,'python':789}
dic2
dic2=dict([('hello',123),('world',456)])
dic2

Python基础——字典(dict) Python 第2张

赋值

 

dic1['first']=123
dic1

 

dic1['python']=456
dic1

 

Python基础——字典(dict) Python 第3张

根据键取值

方法1:

若键不存在,则报错。

 

dic1['python']

 

Python基础——字典(dict) Python 第4张

方法2:

若键不存在,则输出指定内容。

dic5.get('hello')
dic5.get('test','没有')

Python基础——字典(dict) Python 第5张

Python基础——字典(dict) Python 第6张

值可以是任意类型

list1=[1,2,3]
dic3={}
dic3["hello"]=list1
dic3['world']=5
dic3
dic4={}
dic_sub1={"hello1":123,"world1":456,"python1":789}
dic_sub2={"hello2":213,"world2":546,"python2":879}
dic4["test1"]=dic_sub1
dic4["test2"]=dic_sub2
dic4

Python基础——字典(dict) Python 第7张

键值运算

dic5={'hello':123,'world':456,'python':789}
dic5['hello']+=1
dic5

Python基础——字典(dict) Python 第8张

弹出

dic5.pop('hello')

Python基础——字典(dict) Python 第9张

删除

del dic5['world']

Python基础——字典(dict) Python 第10张

更新值

用字典2中的值更新字典1中的值。字典2中与字典1中的键相同,则该键的值更新为字典2的,若字典2中的键字典1中并没有,那就添加该键值对。字典2不改变。

dic6={'hello':123,'world':456}
dic7={'hello':789,'python':888}
dic6.update(dic7)
dic6

Python基础——字典(dict) Python 第11张

判断键在不在字典中

'hello' in dic7

Python基础——字典(dict) Python 第12张

获取字典中所有的键值

dic7.keys()
dic7.values()
dic7.items()

Python基础——字典(dict) Python 第13张

Python基础——字典(dict) Python 第14张

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄