将键/值从一个字典复制到另一个


问题内容

我有一个主要数据(大致)这样的字典: {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}

我还有另一个像这样的字典: {'UID': 'A12B4', 'other_thing: 'cats'}

我不清楚如何“加入”两个字典,然后将“ other_thing”放入主字典。我需要的是:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}

我对这样的理解还很陌生,但是我的直觉说必须有一条直截了当的方法。


问题答案:

您要使用的dict.update方法:

d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)

输出:

{'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}

文档中

使用其他键/值对更新字典,覆盖现有键。不返回。