python的6種基礎資料型別 (Elementary Data Type)--字典

來源:互聯網
上載者:User

標籤:字典   module   ack   轉換   元祖   inux   none   uil   冒號   

python的6種基礎資料型別 (Elementary Data Type)--字典 字典字典的定義與特性字典是Python語言中唯一的映射類型。 定義:{key1:value1,key2:value2}
1、 鍵與值用冒號":"分開; 2、項與項用逗號","分開;
特性
1.key:value結構 2.key必須可hash、且必須為不可變資料類型、必須唯一(數字、字串、元組) 3.value可存放任意多個值、可修改、可以不唯一 4.無序 
 字典的建立與常見操作 字典的建立 
# a.直接用 {} 建立,key:value對應>>> skills = {"s1":"python","s2":"linux","s3":"html/css","s4":"JavaScript"}>>> skills{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘, ‘s3‘: ‘html/css‘, ‘s4‘: ‘JavaScript‘}# b.用dict轉換>>> skills_1 = dict(s1="python",s2="linux")>>> skills_1{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}>>> skills_1 = dict("s1"="python","s2"="linux")                   # 不能這樣建立,本身有歧義,前後都是兩個字串SyntaxError: keyword can‘t be an expression    # 將本身就是字典轉換成dict   >>> skills_2 = dict({"s1":"python","s2":"linux"})>>> skills_2{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}# 將形如key-value結構的轉換為字典>>> skills_3 = dict((["s1","python"],["s2","linux"]))>>> skills_3{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}>>> skills_3 = dict([["s1","python"],["s2","linux"]])>>> skills_3{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}>>> skills_3 = dict([("s1","python"),("s2","linux")])>>> skills_3{‘s1‘: ‘python‘, ‘s2‘: ‘linux‘}# key 為元組的字典>>> skills_3 = dict([[(1,2),"python"],[(21,21),"linux"]])>>> skills_3{(1, 2): ‘python‘, (21, 21): ‘linux‘}給多個鍵賦相同的值>>> dic = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘,‘linux‘])>>> dic{‘s1‘: [‘python‘, ‘linux‘], ‘s2‘: [‘python‘, ‘linux‘]}dic1 = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘],[‘linux‘])        #最多兩個變數,多了報錯Traceback (most recent call last):                          # 第二個變數是為共用的,當為可變類型時,可以修改添加,修改,  File "<pyshell#71>", line 1, in <module>    dic1 = {}.fromkeys([‘s1‘,‘s2‘],[‘python‘],[‘linux‘])TypeError: fromkeys expected at most 2 arguments, got 3>>> dic[‘s1‘].append(1)>>> dic{‘s1‘: [‘python‘, ‘linux‘, 1], ‘s2‘: [‘python‘, ‘linux‘, 1]}>>> dic[‘s1‘].remove(‘python‘)>>> dic{‘s1‘: [‘linux‘, 1, 1], ‘s2‘: [‘linux‘, 1, 1]}

  

字典的常見操作

 

 1 鍵、值、索引值對 2 dic.keys()       返回一個包含字典所有KEY的列表; 3 dic.values()     返回一個包含字典所有value的列表; 4 dic.items()      返回一個包含所有(鍵,值)元祖的列表; 5  6 >>> skills 7 {‘s1‘: ‘python‘, ‘s2‘: ‘linux‘, ‘s3‘: ‘html/css‘, ‘s4‘: ‘JavaScript‘} 8 >>> skills.keys 9 <built-in method keys of dict object at 0x00000209A130DCF0>10 >>> skills.keys()11 dict_keys([‘s1‘, ‘s2‘, ‘s3‘, ‘s4‘])12 >>> skills.values()13 dict_values([‘python‘, ‘linux‘, ‘html/css‘, ‘JavaScript‘])14 >>> skills.items()15 dict_items([(‘s1‘, ‘python‘), (‘s2‘, ‘linux‘), (‘s3‘, ‘html/css‘), (‘s4‘, ‘JavaScript‘)])16 17 新增18 dic[‘new_key‘] = ‘new_value‘19 dic.setdefault(key,None)    如果字典中不存在Key鍵,由 dic[key] = default 為它賦值,這裡defalut=None,實際建立需要填value20 21 22 修改23 dic[‘key‘] = ‘new_values‘    如果key在字典中存在,‘new_value‘將會替代原來的value值,不存在則建立24 dic.update(dic2)         將字典dic2的索引值對添加到字典dic中25 26 查看27 dic[‘key‘]        返回字典中key對應的值,若key不存在字典中,則報錯;28 dict.get(key,default = None)        返回字典中key對應的值,若key不存在字典中,則返回default的值(default預設為None)29 30 31 迴圈(3)32 a.  for i in dic.keys()    等同於 for i in dic33 >>> for k in skills.keys():print(k)34 s135 s236 s337 s438 >>> for k in skills:print(k)39 s140 s241 s342 s443 44 b.  for k,v in dic.items()45 46 >>> for k,v in skills.items():print(k,v)47 s1 python48 s2 linux49 s3 docker50 s4 JavaScript51 c.52 >>> for k,v in enumerate(skills):print(k,v)53 54 0 s155 1 s256 2 s357 3 s458 >>> for k,v,j in enumerate(skills):print(k,v,j)59 60 Traceback (most recent call last):61   File "<pyshell#48>", line 1, in <module>62     for k,v,j in enumerate(skills):print(k,v,j)63 ValueError: not enough values to unpack (expected 3, got 2)64 65 66 長度67 len(dic)

 

 

 

 

 

python的6種基礎資料型別 (Elementary Data Type)--字典

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.