2014-02-12 103 views
4

我有主數據(粗略地)一個字典作爲這樣:{'UID': 'A12B4', 'name': 'John', 'email': '[email protected]}複製從一個字典中的鍵/值到另一個

和我有另一個字典等:{'UID': 'A12B4', 'other_thing: 'cats'}

我不清楚如何「加入「這兩個詞,然後把」其他的東西「,以主要的字典。我需要的是:{'UID': 'A12B4', 'name': 'John', 'email': '[email protected], 'other_thing': 'cats'}

我對這樣的理解很新,但我的直覺告訴我必須有一個簡單的方法。

回答

13

要使用dict.update方法:

d1 = {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]'} 
d2 = {'UID': 'A12B4', 'other_thing': 'cats'} 
d1.update(d2) 

輸出:

{'email': '[email protected]', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'} 

Docs

更新字典與其他鍵/值對,覆蓋現有的密鑰。返回無。

+0

爆炸,歡呼的人,這是什麼,我只是無法得到。簡單性。謝謝。 – BryanGrimes

+0

@mhlester:如果我只想複製從d1到d2的前兩個值,該怎麼辦? –

+1

@ClintWhaley它聽起來像你問一個[新問題](http://stackoverflow.com/questions/ask) – mhlester

2

如果你想加入字典,有一個偉大的內置功能,您可以打電話,叫update

具體做法是:

​​
相關問題