将键/值从一个字典复制到另一个 [英] Copying a key/value from one dictionary into another
问题描述
我有一个字典(大致),如下所示:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}
I have a dict with main data (roughly) as such: {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com}
我还有另一个像这样的字典:{'UID': 'A12B4', 'other_thing: 'cats'}
and I have another dict like: {'UID': 'A12B4', 'other_thing: 'cats'}
我不清楚如何加入"两个字典,然后将"other_thing"放入主字典.我需要的是:{'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}
I'm unclear how to "join" the two dicts to then put "other_thing" to the main dict. What I need is: {'UID': 'A12B4', 'name': 'John', 'email': 'hi@example.com, 'other_thing': 'cats'}
我对这样的理解还很陌生,但是我的直觉说必须要有一条直截了当的方法.
I'm pretty new to comprehensions like this, but my gut says there has to be a straight forward way.
推荐答案
您要使用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'}
从文档:
使用其他键/值对更新字典,覆盖现有键.不返回任何内容.
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
这篇关于将键/值从一个字典复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!