Python 将一个字典中的键/值复制到另一个字典中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21719842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying a key/value from one dictionary into another
提问by bryan
I have a dict with main data (roughly) as such: {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]}
我有一个包含主要数据的字典(大致)如下: {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]}
and I have another dict like: {'UID': 'A12B4', 'other_thing: 'cats'}
我还有另一个 dict 像: {'UID': 'A12B4', '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': '[email protected], 'other_thing': 'cats'}
我不清楚如何“加入”两个字典,然后将“other_thing”放入主字典。我需要的是:{'UID': 'A12B4', 'name': 'John', 'email': '[email protected], 'other_thing': 'cats'}
I'm pretty new to comprehensions like this, but my gut says there has to be a straight forward way.
我对这样的理解很陌生,但我的直觉说必须有一个直接的方法。
采纳答案by mhlester
you want to use the dict.updatemethod:
你想使用的dict.update方法:
d1 = {'UID': 'A12B4', 'name': 'John', 'email': '[email protected]'}
d2 = {'UID': 'A12B4', 'other_thing': 'cats'}
d1.update(d2)
Outputs:
输出:
{'email': '[email protected]', 'other_thing': 'cats', 'UID': 'A12B4', 'name': 'John'}
From the Docs:
从文档:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
使用其他键/值对更新字典,覆盖现有键。返回无。
回答by Slater Victoroff
If you want to join dictionaries, there's a great built-in function you can call, called update.
如果你想加入字典,你可以调用一个很棒的内置函数,叫做update.
Specifically:
具体来说:
test = {'A': 1}
test.update({'B': 2})
test
>>> {'A':1, 'B':2}

![Python OSError: [WinError 193] %1 不是有效的 Win32 应用程序](/res/img/loading.gif)