Dictionary
A dictionary is another mutable container model and can store any type of object.
Each key value of the dictionary (Key=>value) is split with a colon (:), each pair is separated by a comma (,), and the entire dictionary is included in curly braces ({})
Grammar:
1 goods = {2 'apple': 4.5,3 ' Orange': 2.3,4 'banana' : 3.55 }
Features of the dictionary:
- Dict is disordered.
- Key must be unique
1. Adding elements
1>>>Goods2{'Apple': 4.5,'Banana': 3.5,'Orange': 2.3}3>>> goods['Peach']=5.04>>>Goods5{'Apple': 4.5,'Banana': 3.5,'Orange': 2.3,'Peach': 5.0}
2. Modifications
1 >>> goods['apple']=5.5 # Change Apple's price to 5.52 >>> Goods3 {'apple'Banana 'Orange''peach': 5.0}
3. Deleting an element
1>>>Goods2{'Apple': 5.5,'Banana': 3.5,'Orange': 2.3,'Peach': 5.0}3>>> Goods.pop ('Peach')#deletes the last one and returns the value45.05>>>Goods6{'Apple': 5.5,'Banana': 3.5,'Orange': 2.3}7 8>>>delgoods['Banana']#specify the deletion of key9>>>GoodsTen{'Apple': 5.5,'Orange': 2.3} One A>>>Goods -{'Apple': 5.5,'Grape': 6.0,'Orange': 2.3,'Watermelon': 12.0} ->>> Goods.popitem ()#Random Delete the('Apple', 5.5) ->>>Goods -{'Grape': 6.0,'Orange': 2.3,'Watermelon': 12.0}
4. Find
1>>>Goods2{'Grape': 6.0,'Orange': 2.3,'Watermelon': 12.0}3>>>'Grape' inchGoods4 True5>>> Goods.get ('Orange')#know key, get value62.37>>> goods['Watermelon']812.09>>> goods['Apple']#If a key does not exist, it will be an error, get will not, does not exist will only return noneTen Traceback (most recent): OneFile"<stdin>", Line 1,inch<module> AKeyerror:'Apple'
5. Multi-level dictionary and operation
1Area = {'Zhejiang':2 {3 'Hangzhou':['West L. District','Xiacheng District','Xiaoshan District'],4 'Jiaxing':['Nanhu District','Xiuzhou District','Pinghu'],5 'Wenzhou':['Nine Bay Area','Lucheng District','Dongtou District']6 },7 'Jiangsu':8 {9 'Nanjing':['gu Lou','Xuanwu District','Qinhuai District'],Ten 'Suzhou':['gu Soviet area','Wuzhong District','Huqiu District'], One 'Changzhou':['Wujin District','Jintan','Liyang'] A } - - the } - ->>> area['Zhejiang']['Hangzhou'] -['West L. District','Xiacheng District','Xiaoshan District'] + - +>>> area['Zhejiang']['Hangzhou'][1] + =', very large' A>>> area['Zhejiang']['Hangzhou'] at['West L. District','Xiacheng District, very big.','Xiaoshan District']
6. Other uses
1>>>Area.keys ()2Dict_keys (['Zhejiang','Jiangsu'])3>>>goods.values ()4Dict_values ([6.0, 2.3, 12.0])5>>>Goods.keys ()6Dict_keys (['Grape','Orange','Watermelon'])7 8{'Grape': 6.0,'Orange': 2.3,'Watermelon': 12.0}9>>> B = {1:2,3:4,'Grape': 4.5}Ten>>>Goods.update (b) One>>>Goods A{1:2, 3:4,'Grape': 4.5,'Orange': 2.3,'Watermelon': 12.0} - ->>>Goods.items () theDict_items ([(1, 2), (3, 4), ('Grape', 4.5), ('Orange', 2.3), ('Watermelon', 12.0)])
7. Traversing a dictionary
1 for inch Goods: 2 Print (Key,goods[key]) 3 #或4 for in Goods.items ():5 Print (K,V)
Python Base 2--Dictionary