Skip to content

Commit 03a7efd

Browse files
authored
Merge pull request #532 from groutr/merge_with_defaultdict
Use defaultdict for collecting intermediate values in merge_with
2 parents 142e9ee + 6509be5 commit 03a7efd

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

toolz/dicttoolz.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import operator
2+
import collections
23
from functools import reduce
34
from collections.abc import Mapping
45

@@ -58,14 +59,15 @@ def merge_with(func, *dicts, **kwargs):
5859
dicts = dicts[0]
5960
factory = _get_factory(merge_with, kwargs)
6061

61-
result = factory()
62+
values = collections.defaultdict(lambda: [].append)
6263
for d in dicts:
6364
for k, v in d.items():
64-
if k not in result:
65-
result[k] = [v]
66-
else:
67-
result[k].append(v)
68-
return valmap(func, result, factory)
65+
values[k](v)
66+
67+
result = factory()
68+
for k, v in values.items():
69+
result[k] = func(v.__self__)
70+
return result
6971

7072

7173
def valmap(func, d, factory=dict):

0 commit comments

Comments
 (0)