我有一个主要数据的字典(大致)如下: {'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'}
我对这样的理解很新,但我的直觉说必须有一种直截了当的方式.
mhl*_*ter 21
你想使用这个dict.update方法:
d1 = {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)
Run Code Online (Sandbox Code Playgroud)
输出:
{'email': 'hi@example.com', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}
Run Code Online (Sandbox Code Playgroud)
来自Docs:
使用其他键中的键/值对更新字典,覆盖现有键.返回无.