Python字典增刪操作技巧簡(jiǎn)述
Python編程語(yǔ)言是一款比較容易學(xué)習(xí)的計(jì)算機(jī)通用型語(yǔ)言。對(duì)于初學(xué)者來(lái)說(shuō),首先需要掌握的就是其中的一些基礎(chǔ)應(yīng)用。比如今天我們?yōu)榇蠹医榻B的Python字典的相關(guān)操作,就是我們?cè)趯W(xué)習(xí)過(guò)程中需要熟練掌握的技巧。
Python字典(Dictionary)是一種映射結(jié)構(gòu)的數(shù)據(jù)類型,由無(wú)序的“鍵-值對(duì)”組成。字典的鍵必須是不可改變的類型,如:字符串,數(shù)字,tuple;值可以為任何Python數(shù)據(jù)類型。
1、新建Python字典
- >>> dict1={} #建立一個(gè)空字典
- >>> type(dict1)
- < type 'dict'>
2、增加Python字典元素:兩種方法
- >>> dict1['a']=1 #第一種
- >>> dict1
- {'a': 1}
- #第二種:setdefault方法
- >>> dict1.setdefault('b',2)
- 2
- >>> dict1
- {'a': 1, 'b': 2}
3、刪除Python字典
- #刪除指定鍵-值對(duì)
- >>> dict1
- {'a': 1, 'b': 2}
- >>> del dict1['a'] #也可以用pop方法,dict1.pop('a')
- >>> dict1
- {'b': 2}
- #清空字典
- >>> dict1.clear()
- >>> dict1 #字典變?yōu)榭樟?
- {}
- #刪除字典對(duì)象
- >>> del dict1
- >>> dict1
- Traceback (most recent call last):
- File "< interactive input>", line 1, in < module>
- NameError: name 'dict1' is not defined
以上就是對(duì)Python字典的相關(guān)內(nèi)容的介紹。
【編輯推薦】