【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參數的用法