例如我有两个字典:
Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}
我需要一种“组合”两个字典的pythonic方式,结果是:
{'a': 1, 'b': 5, 'c': 7, 'd': 5}
也就是说:如果一个键出现在两个dict中,则添加它们的值,如果它只出现在一个dict中,则保留其值。
例如我有两个字典:
Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}
我需要一种“组合”两个字典的pythonic方式,结果是:
{'a': 1, 'b': 5, 'c': 7, 'd': 5}
也就是说:如果一个键出现在两个dict中,则添加它们的值,如果它只出现在一个dict中,则保留其值。
>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
Counters 基本上是 的子类dict
,因此您仍然可以使用它们执行通常使用该类型执行的所有其他操作,例如迭代它们的键和值。
一个更通用的解决方案,它也适用于非数字值:
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
r = dict(a.items() + b.items() +
[(k, a[k] + b[k]) for k in set(b) & set(a)])
甚至更通用:
def combine_dicts(a, b, op=operator.add):
return dict(a.items() + b.items() +
[(k, op(a[k], b[k])) for k in set(b) & set(a)])
例如:
>>> a = {'a': 2, 'b':3, 'c':4}
>>> b = {'a': 5, 'c':6, 'x':7}
>>> import operator
>>> print combine_dicts(a, b, operator.mul)
{'a': 10, 'x': 7, 'c': 24, 'b': 3}
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
简介: 有(可能)最好的解决方案。但是您必须知道并记住它,有时您必须希望您的 Python 版本不会太旧或任何问题。
然后是最“hacky”的解决方案。它们又好又短,但有时难以理解、阅读和记忆。
不过,还有另一种选择,那就是尝试重新发明轮子。- 为什么要重新发明轮子?- 通常是因为它是一种非常好的学习方式(有时只是因为现有工具不能完全按照您的意愿和/或您希望的方式进行操作),如果您不知道或不知道,这是最简单的方法不记得解决问题的完美工具。
所以,我建议从模块中重新发明Counter
课程的轮子collections
(至少部分):
class MyDict(dict):
def __add__(self, oth):
r = self.copy()
try:
for key, val in oth.items():
if key in r:
r[key] += val # You can custom it here
else:
r[key] = val
except AttributeError: # In case oth isn't a dict
return NotImplemented # The convention when a case isn't handled
return r
a = MyDict({'a':1, 'b':2, 'c':3})
b = MyDict({'b':3, 'c':4, 'd':5})
print(a+b) # Output {'a':1, 'b': 5, 'c': 7, 'd': 5}
可能会有其他方法来实现这一点,并且已经有工具可以做到这一点,但可视化事情的基本运作方式总是很好的。
在这种情况下,绝对对 s 求和Counter()
是最 Pythonic 的方法,但前提是它会产生一个正值。c
这是一个示例,您可以看到在否定字典中c
的值后没有结果。B
In [1]: from collections import Counter
In [2]: A = Counter({'a':1, 'b':2, 'c':3})
In [3]: B = Counter({'b':3, 'c':-4, 'd':5})
In [4]: A + B
Out[4]: Counter({'d': 5, 'b': 5, 'a': 1})
这是因为Counter
s 主要设计用于使用正整数来表示运行计数(负计数没有意义)。但是为了帮助这些用例,python 记录了最小范围和类型限制,如下所示:
- Counter 类本身是一个字典子类,对其键和值没有限制。这些值旨在是表示计数的数字,但您可以在值字段中存储任何内容。
- 该
most_common()
方法只要求值是可排序的。- 对于诸如 的就地操作
c[key]
+= 1
,值类型只需要支持加法和减法即可。所以分数、浮点数和小数都可以使用,并且支持负值。update()
对于输入和subtract()
输出都允许负值和零值也是如此。- 多集方法仅适用于具有正值的用例。输入可能是负数或零,但只会创建具有正值的输出。没有类型限制,但是值类型需要支持加减比较。
- 该
elements()
方法需要整数计数。它忽略零计数和负计数。
因此,为了在对您的 Counter 求和后解决该问题,您可以使用Counter.update
它来获得所需的输出。它的工作方式类似dict.update()
,但增加了计数而不是替换它们。
In [24]: A.update(B)
In [25]: A
Out[25]: Counter({'d': 5, 'b': 5, 'a': 1, 'c': -1})
myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
myDict[k] = A.get(k, 0)+B.get(k, 0)
没有额外进口的那一款!
他们是一个名为EAFP的Python 标准(请求宽恕比许可更容易)。下面的代码基于该python 标准。
# The A and B dictionaries
A = {'a': 1, 'b': 2, 'c': 3}
B = {'b': 3, 'c': 4, 'd': 5}
# The final dictionary. Will contain the final outputs.
newdict = {}
# Make sure every key of A and B get into the final dictionary 'newdict'.
newdict.update(A)
newdict.update(B)
# Iterate through each key of A.
for i in A.keys():
# If same key exist on B, its values from A and B will add together and
# get included in the final dictionary 'newdict'.
try:
addition = A[i] + B[i]
newdict[i] = addition
# If current key does not exist in dictionary B, it will give a KeyError,
# catch it and continue looping.
except KeyError:
continue
编辑:感谢jerzyk的改进建议。
import itertools
import collections
dictA = {'a':1, 'b':2, 'c':3}
dictB = {'b':3, 'c':4, 'd':5}
new_dict = collections.defaultdict(int)
# use dict.items() instead of dict.iteritems() for Python3
for k, v in itertools.chain(dictA.iteritems(), dictB.iteritems()):
new_dict[k] += v
print dict(new_dict)
# OUTPUT
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
或者
或者,您可以使用上面提到的 @Martijn 的 Counter 。
对于更通用和可扩展的方式检查mergedict。它使用singledispatch
并可以根据其类型合并值。
例子:
from mergedict import MergeDict
class SumDict(MergeDict):
@MergeDict.dispatch(int)
def merge_int(this, other):
return this + other
d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})
assert d2 == {'a': 3, 'b': 'two'}
感谢@tokeinizer_fsj 在评论中告诉我我没有完全理解问题的含义(我认为 add 意味着只是添加最终在两个字典中不同的键,相反,我的意思是公共键值应该相加)。所以我在合并之前添加了那个循环,这样第二个字典就包含了公共键的总和。最后一个字典将是其值将在新字典中持续存在的字典,这是两者合并的结果,所以我认为问题已解决。该解决方案从 python 3.5 及以下版本开始有效。
a = {
"a": 1,
"b": 2,
"c": 3
}
b = {
"a": 2,
"b": 3,
"d": 5
}
# Python 3.5
for key in b:
if key in a:
b[key] = b[key] + a[key]
c = {**a, **b}
print(c)
>>> c
{'a': 3, 'b': 5, 'c': 3, 'd': 5}
a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 3, 'c': 4, 'd': 5}
def mergsum(a, b):
for k in b:
if k in a:
b[k] = b[k] + a[k]
c = {**a, **b}
return c
print(mergsum(a, b))
此外,请注意a.update( b )
2x 比a + b
from collections import Counter
a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
b = Counter({'menu': 1, 'good': 1, 'bar': 3})
%timeit a + b;
## 100000 loops, best of 3: 8.62 µs per loop
## The slowest run took 4.04 times longer than the fastest. This could mean that an intermediate result is being cached.
%timeit a.update(b)
## 100000 loops, best of 3: 4.51 µs per loop
def merge_with(f, xs, ys):
xs = a_copy_of(xs) # dict(xs), maybe generalizable?
for (y, v) in ys.iteritems():
xs[y] = v if y not in xs else f(xs[x], v)
merge_with((lambda x, y: x + y), A, B)
你可以很容易地概括这一点:
def merge_dicts(f, *dicts):
result = {}
for d in dicts:
for (k, v) in d.iteritems():
result[k] = v if k not in result else f(result[k], v)
然后它可以接受任意数量的字典。
这是一个简单的解决方案,用于合并两个+=
可以应用于值的字典,它只需要遍历字典一次
a = {'a':1, 'b':2, 'c':3}
dicts = [{'b':3, 'c':4, 'd':5},
{'c':9, 'a':9, 'd':9}]
def merge_dicts(merged,mergedfrom):
for k,v in mergedfrom.items():
if k in merged:
merged[k] += v
else:
merged[k] = v
return merged
for dct in dicts:
a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}
该解决方案易于使用,用作普通字典,但您可以使用 sum 函数。
class SumDict(dict):
def __add__(self, y):
return {x: self.get(x, 0) + y.get(x, 0) for x in set(self).union(y)}
A = SumDict({'a': 1, 'c': 2})
B = SumDict({'b': 3, 'c': 4}) # Also works: B = {'b': 3, 'c': 4}
print(A + B) # OUTPUT {'a': 1, 'b': 3, 'c': 6}
关于什么:
def dict_merge_and_sum( d1, d2 ):
ret = d1
ret.update({ k:v + d2[k] for k,v in d1.items() if k in d2 })
ret.update({ k:v for k,v in d2.items() if k not in d1 })
return ret
A = {'a': 1, 'b': 2, 'c': 3}
B = {'b': 3, 'c': 4, 'd': 5}
print( dict_merge_and_sum( A, B ) )
输出:
{'d': 5, 'a': 1, 'c': 7, 'b': 5}
一种解决方案是使用字典理解。
C = { k: A.get(k,0) + B.get(k,0) for k in list(B.keys()) + list(A.keys()) }
上述解决方案非常适合您拥有少量Counter
s 的场景。如果你有一个很大的列表,这样的事情会更好:
from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
C = Counter({'a': 5, 'e':3})
list_of_counts = [A, B, C]
total = sum(list_of_counts, Counter())
print(total)
# Counter({'c': 7, 'a': 6, 'b': 5, 'd': 5, 'e': 3})
上述解决方案本质上Counter
是通过以下方式对 s 求和:
total = Counter()
for count in list_of_counts:
total += count
print(total)
# Counter({'c': 7, 'a': 6, 'b': 5, 'd': 5, 'e': 3})
这做同样的事情,但我认为它总是有助于了解它在下面有效地做了什么。
结合两个dict的更传统的方式。使用模块和工具很好,但如果您不记得这些工具,了解其背后的逻辑会有所帮助。
程序结合两个字典添加公共键的值。
def combine_dict(d1,d2):
for key,value in d1.items():
if key in d2:
d2[key] += value
else:
d2[key] = value
return d2
combine_dict({'a':1, 'b':2, 'c':3},{'b':3, 'c':4, 'd':5})
output == {'b': 5, 'c': 7, 'd': 5, 'a': 1}
这是一个非常通用的解决方案。您可以处理仅在某些 dict + 中的任意数量的 dict + 键,轻松使用您想要的任何聚合函数:
def aggregate_dicts(dicts, operation=sum):
"""Aggregate a sequence of dictionaries using `operation`."""
all_keys = set().union(*[el.keys() for el in dicts])
return {k: operation([dic.get(k, None) for dic in dicts]) for k in all_keys}
例子:
dicts_same_keys = [{'x': 0, 'y': 1}, {'x': 1, 'y': 2}, {'x': 2, 'y': 3}]
aggregate_dicts(dicts_same_keys, operation=sum)
#{'x': 3, 'y': 6}
示例不同的键和通用聚合:
dicts_diff_keys = [{'x': 0, 'y': 1}, {'x': 1, 'y': 2}, {'x': 2, 'y': 3, 'c': 4}]
def mean_no_none(l):
l_no_none = [el for el in l if el is not None]
return sum(l_no_none) / len(l_no_none)
aggregate_dicts(dicts_diff_keys, operation=mean_no_none)
# {'x': 1.0, 'c': 4.0, 'y': 2.0}
在没有任何其他模块或库的情况下将三个字典 a、b、c 合并在一行中
如果我们有这三个字典
a = {"a":9}
b = {"b":7}
c = {'b': 2, 'd': 90}
用一行合并所有内容并使用返回一个 dict 对象
c = dict(a.items() + b.items() + c.items())
返回
{'a': 9, 'b': 2, 'd': 90}