python的三種創建字典的方法


#創建一個空字典
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
復制代碼

 


免責聲明!

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



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