添加
xxx[新的key] = value 刪除 del xx[key] 修改 xxx[已存在的key] = new_value 查詢 xxx.get(key)
#### list 列表存儲數據 In [4]: stu001 = ["alex",18,"北京"] In [5]: print("%s的年齡是%d,家住在%s"%(stu001[0],stu001[1],stu001[2])) alex的年齡是18,家住在北京 ##### dict 字典存儲數據 In [6]: #字典 In [7]: #info = {鍵:值,鍵:值} key:value 鍵值對 In [8]: stu001 = {"name":"alex","age":18,"home":"beijing"} In [12]: print("%s的年齡是%d,家在%s"%(stu001["name"],stu001["age"],stu001["home"])) alex的年齡是18,家在beijing
######## 增長 xxx[新的key] = value In [1]: infor = {"name":"alex"} In [2]: infor["age"] = 18 In [3]: infor Out[3]: {'name': 'alex', 'age': 18} In [4]: infor["QQ"] = 10086 In [5]: infor Out[5]: {'QQ': 10086, 'name': 'alex', 'age': 18}
######### 刪除 del xxx[已存在的key] ######### 刪除 del xxx[不存在的key] 報錯 In [8]: del infor["QQ"] In [9]: infor Out[9]: {'name': 'alex', 'age': 18} In [10]: del infor["QQ"] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-10-1c0f878ade5a> in <module>() ----> 1 del infor["QQ"] KeyError: 'QQ'
######### 修改 xxx[已存在的key] = new_value In [6]: infor["QQ"] = 8888 In [7]: infor Out[7]: {'QQ': 8888, 'name': 'alex', 'age': 18}
######### 查詢 不正確用法 infor["QQ"] In [11]: infor Out[11]: {'name': 'alex', 'age': 18} In [12]: infor["name"] Out[12]: 'alex' In [13]: infor["age"] Out[13]: 18 In [14]: infor["QQ"] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-14-8398698e14db> in <module>() ----> 1 infor["QQ"] KeyError: 'QQ' ######## 查詢 標準用法 infor.get("QQ") In [15]: infor.get("QQ") In [16]: infor.get("name") Out[16]: 'alex' In [17]: infor.get("age") Out[17]: 18