我想合并两个Python词典添加剂,如下所示:
a = {'result': {'sessionId': '111'}}
b = {'result': {'completelyOtherSessionId': '100'}}
##magic##
c = {'result': {'sessionId': '111', 'completelyOtherSessionId': '100'}}
答案 0 :(得分:2)
template<class T>
class nodo{
public:
T data;
};
请理解此解决方案仅适用于您的具体情况(>>> a = {'result': {'sessionId': '111'}}
>>> b = {'result': {'sessionsId': '100'}}
>>> с = a.copy()
>>> for key in c:
>>> c[key].update(b[key])
>>> print(c)
{'result': {'sessionId': '111', 'sessionsId': '100'}}
和a
的值也是字典)。否则,b
方法将无效,您将获得update
例外。
答案 1 :(得分:0)
这是一个Python2 / 3函数,它不会改变你提供的dicts。它将创建一个新的并尝试将它们组合在一起。请记住,它不会以任何高级方式处理冲突。它只是用最右边的dict参数覆盖它。
def add_dicts(*dicts):
ret, dicts = dict(), list(dicts)
dicts.insert(0, ret)
try:
red = reduce
except NameError:
red = __import__("functools").reduce
red(lambda x, y: x.update(y) or x, dicts)
return ret
示例:
a = {"a": 1}
b = {"b": 2}
c = {"c": 3}
var = add_dicts(a, b, c)
print(a) # => {"a": 1}
print(b) # => {"b": 2}
print(c) # => {"c": 3}
print(var) # => {'a': 1, 'c': 3, 'b': 2}