我有
dict1 = {a: 1, b: 2, c: 3}
dict2 = {b: 3, c: 2}
如何合并dict1和dict2,以便结果dict3具有{a:1,b:3,c:3} 我知道我们可以像dict3 = {** a,** b}这样合并,但是在任何地方都必须写一个条件才能使其适用于我的问题吗?
我有
dict1 = {a: 1, b: 2, c: 3}
dict2 = {b: 3, c: 2}
如何合并dict1和dict2,以便结果dict3具有{a:1,b:3,c:3} 我知道我们可以像dict3 = {** a,** b}这样合并,但是在任何地方都必须写一个条件才能使其适用于我的问题吗?
You could simply loop through them and compare the values, and use
dict.setdefault(key, 0)
to get around unset values.干得好:
我使用默认的get:dict1.get(k,DEFAULT)并将两个键集与´|`运算符连接在一起。