[Python Study Notes]字典操作

來源:互聯網
上載者:User

標籤:blog   import   body   items   note   字典   修改   long   ict   

                      字典操作                                                                       

 

a.增加
1 >>> info["stu1104"] = "abc"2 >>> info3 {‘stu1102‘: ‘x5456‘, ‘stu1104‘: ‘abc‘, ‘stu1103‘: ‘Mali‘, ‘stu1101‘: ‘Wu‘}
 b.修改
1 >>> info[‘stu1101‘] = "xinge"2 >>> info3 {‘stu1102‘: ‘x5456‘, ‘stu1103‘:  Mali‘, ‘stu1101‘: ‘xinge‘}
 c.刪除
 1 >>> info 2 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤蘭‘} 3 >>> info.pop("stu1101") #標準刪除姿勢 4 ‘武藤蘭‘ 5 >>> info 6 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} 7 >>> del info[‘stu1103‘] #換個姿勢刪除 8 >>> info 9 {‘stu1102‘: ‘LongZe Luola‘}10 >>> 11 >>> 12 >>> 13 >>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘}14 >>> info15 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} #隨機刪除16 >>> info.popitem()17 (‘stu1102‘, ‘LongZe Luola‘)18 >>> info19 {‘stu1103‘: ‘XiaoZe Maliya‘}
 d.尋找
 1 >>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} 2 >>>  3 >>> "stu1102" in info #標準用法 4 True 5 >>> info.get("stu1102")  #擷取 6 ‘LongZe Luola‘ 7 >>> info["stu1102"] #同上,但是看下面 8 ‘LongZe Luola‘ 9 >>> info["stu1105"]  #如果一個key不存在,就報錯,get不會,不存在只返回None10 Traceback (most recent call last):11   File "<stdin>", line 1, in <module>12 KeyError: ‘stu1105‘
 e.擷取索引值
1 #values2 >>> info.values()3 dict_values([‘LongZe Luola‘, ‘XiaoZe Maliya‘])4 5 #keys6 >>> info.keys()7 dict_keys([‘stu1102‘, ‘stu1103‘])

 

f.合并
1 #update 2 >>> info3 {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}4 >>> b = {1:2,3:4, "stu1102":"龍澤蘿拉"}5 >>> info.update(b)6 >>> info7 {‘stu1102‘: ‘龍澤蘿拉‘, 1: 2, 3: 4, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘}

 

g.深copy
1 import copy2    3 n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}4    5 n4 = copy.deepcopy(n1)

 

h.迴圈
1 #方法12 for key in info:3     print(key,info[key])4  5 #方法26 for k,v in info.items(): #會先把dict轉成list,資料裡大時莫用7     print(k,v)

 

[Python Study Notes]字典操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.