【Python—字典的用法】建立字典的3種方法,python3種

來源:互聯網
上載者:User

【Python—字典的用法】建立字典的3種方法,python3種

 

#建立一個空字典empty_dict = dict() print(empty_dict)#用**kwargs可變參數傳入關鍵字建立字典a = dict(one=1,two=2,three=3) print(a)#傳入可迭代對象b = dict(zip(['one','two','three'],[1,2,3]))print(list(zip(['one','two','three'],[1,2,3])))print(b)#傳入可迭代對象 c = dict([('one', 1), ('two', 2), ('three', 3)])print(c)c1 = dict([('one', 1), ('two', 2), ('three', 3),('three', 4),('three', 5)])print(c1)#如果鍵有重複,其值為最後重複項的值。 

#傳入映射對象,字典建立字典 d = dict({'one': 1, 'two': 2, 'three': 3}) print(d) print(a == b == c == d)

輸出:

{}{'one': 1, 'two': 2, 'three': 3}[('one', 1), ('two', 2), ('three', 3)]{'one': 1, 'two': 2, 'three': 3}{'one': 1, 'two': 2, 'three': 3}{'one': 1, 'two': 2, 'three': 5}{'one': 1, 'two': 2, 'three': 3}True

 

知識點:

class dict(**kwarg)class dict(mapping, **kwarg)class dict(iterable, **kwarg)

在python中,*arg表示任意多個無名參數,類型為tuple;**kwargs表示關鍵字參數,為dict。參考【Python—參數】*arg與**kwargs參數的用法

在python官方文檔中說明,如果傳入的是可迭代對象,則可迭代對象中的每一項自身必須是可迭代的,並且每一項只能有兩個對象。第一個對象成為新字典的鍵,第二個對象成為其鍵對應的值。如果鍵有重複,其值為最後重複項的值。

 

# 用 class dict(mapping, **kwarg) 建立一個並集字典,會影響相同鍵不同值的項  union = dict(s1,**s2)  print (union)

輸出:

{'d': 4, 'a': 3, 'e': 3, 'f': 4, 'c': 4, 'b': 3}

 知識點:

在函數調用時,**會以鍵/值對的形式解包一個字典,使其成為獨立的關鍵字參數。參考【Python—參數】*arg與**kwargs參數的用法

聯繫我們

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