【Python—字典的用法】創建字典的3種方法


 

#創建一個空字典
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參數的用法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM