2015-12-02 66 views
3

閱讀Python文檔,並且有幾種創建字典的方法。dict(映射,** kwargs)vs dict(可迭代,** kwargs)

dict() 
dict(**kwargs) 
dict(mapping, **kwargs) 
dict(iterable, **kwargs) 

https://docs.python.org/2/library/stdtypes.html(5.8映射類型)

我不理解mappingiterable之間的差 - 文檔讀取:

如果一個位置參數,並給出它是一個映射對象,使用與映射對象相同的鍵值對創建字典。否則,位置參數必須是可迭代的對象。迭代器中的每個項目本身必須是一個具有兩個對象的迭代器。

在我看來,那mappingiterable在這裏一樣的東西......你可以幫我理解上的差異?

+1

「目前只有一個標準映射類型,詞典。 「我認爲這裏的文檔很清楚(https://docs.python.org/2/library/stdtypes.html#mapping-types-dict) –

+0

@ Mr.E - 是的,OP將問題鏈接到問題中。他引用的片段來自該部分。 – TigerhawkT3

+0

@ TigerhawkT3意外地只發送鏈接:P。更正了它 –

回答

3

我不明白,映射和迭代

映射之間的差別是鍵/值對允許值鍵訪問的集合 - 它的「映射」鍵的值。內部類型最明顯的mappingdict

迭代器是一個可迭代的對象 - 這基本上意味着您可以在for obj in iterable:語句中使用它。這包括序列類型(字符串,列表等)以及其他一些(文件,dbapi遊標,生成器等),也包括字典。

0

讓我們看一些例子:

字典()

a=dict() ---> {}

字典(** kwargs)

a=dict(one=1, two=2, three=3) ---> {'one':1,'two':2,'three':3}

字典(映射,** kwargs)

a=dict({'one':1, 'two':2, 'three':3}) ---> { '一':1, '二':2 '3':3}

a=dict({'one':1, 'two':2, 'three':3}, four=4,five=5,six=6) ---> {{ 'one':1,'two':2,'3':3,'four':4,'five':5,'six':6}

dict(iterable,** kwarg)

a=dict([('one',1),('two',2),('three',3)]) ---> { '一':1, '二':2 '3':3}

a=dict((['one',1],['two',2],['three',3])) ---> { '一':1, '二':2 '3':3}

a=dict([('one',1),('two',2),('three',3)], four=4,five=5,six=6) ---> { '一':1, '二':2,「三':3,'four':4,'five':5,'six':6}

a=dict((['one',1],['two',2],['three',3]),four=4,five=5,six=6) --->''''':','two':2,'three':3 , '四':4 '5':5 '6':6}


注:

調用字典(可迭代,** kwarg)函數等於--->

d={} 
a=[('one',1),('two',2),('three',3)] 
for k,v in a: 
    d[k]=v 

print(d)