Python基础——字典(dict)

  • 2020 年 1 月 16 日
  • 筆記

由键-值对构建的集合。

创建

dic1={}  type(dic1)
dic2=dict()  type(dic2)

初始化

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

赋值

dic1['first']=123  dic1
dic1['python']=456  dic1

根据键取值

方法1:

若键不存在,则报错。

dic1['python']

方法2:

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

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

值可以是任意类型

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

键值运算

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

弹出

dic5.pop('hello')

删除

del dic5['world']

更新值

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

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

判断键在不在字典中

'hello' in dic7

获取字典中所有的键值

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