Skip to content

Commit 35483ae

Browse files
committed
Add zip_dict
1 parent 062786a commit 35483ae

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

toolz/curried/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
second,
5252
thread_first,
5353
thread_last,
54+
zip_dict
5455
)
5556
from .exceptions import merge, merge_with
5657

toolz/itertoolz.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
'first', 'second', 'nth', 'last', 'get', 'concat', 'concatv',
1515
'mapcat', 'cons', 'interpose', 'frequencies', 'reduceby', 'iterate',
1616
'sliding_window', 'partition', 'partition_all', 'count', 'pluck',
17-
'join', 'tail', 'diff', 'topk', 'peek', 'random_sample')
17+
'join', 'tail', 'diff', 'topk', 'peek', 'random_sample', 'zip_dict')
1818

1919

2020
def remove(predicate, seq):
@@ -1004,3 +1004,14 @@ def random_sample(prob, seq, random_state=None):
10041004
if not hasattr(random_state, 'random'):
10051005
random_state = Random(random_state)
10061006
return filter(lambda _: random_state.random() < prob, seq)
1007+
1008+
1009+
def zip_dict(*dicts):
1010+
if dicts:
1011+
def is_in_all_others_dict(k):
1012+
return all(map(lambda d: k in d, dicts[1:]))
1013+
1014+
common_keys = filter(is_in_all_others_dict, dicts[0].keys())
1015+
1016+
for k in common_keys:
1017+
yield k, tuple(map(lambda d: d[k], dicts))

toolz/tests/test_itertoolz.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
reduceby, iterate, accumulate,
1414
sliding_window, count, partition,
1515
partition_all, take_nth, pluck, join,
16-
diff, topk, peek, random_sample)
16+
diff, topk, peek, random_sample, zip_dict)
1717
from toolz.compatibility import range, filter
1818
from operator import add, mul
1919

@@ -123,6 +123,21 @@ def test_isdistinct():
123123
assert isdistinct(iter([1, 2, 1])) is False
124124

125125

126+
def test_zip_dict ():
127+
assert tuple(zip_dict()) == ()
128+
assert tuple(zip_dict({0: 0})) == ((0, (0 ,)),)
129+
assert tuple(zip_dict({0: 0}, {1: 1})) == ()
130+
assert tuple(zip_dict({0: 0}, {0: 1})) == ((0, (0 , 1 )),)
131+
assert tuple(zip_dict({0: 0}, {0: 0, 1: 1})) == ((0, (0 , 0)),)
132+
assert tuple(zip_dict({0: 1, 1: 2}, {0: 0, 1: 1})) == ((0, (1 , 0)),
133+
(1, (2, 1)))
134+
135+
assert tuple(zip_dict({-1: 0, 0: 0, 1: 1, 2: 2},
136+
{-2: 0, 0: 1, 1: 2, 2: 3},
137+
{-3: 0, 0: 2, 1: 3, 2: 4})) == ((0, (0 , 1, 2)),
138+
(1, (1, 2, 3 )),
139+
(2, (2, 3, 4)))
140+
126141
def test_nth():
127142
assert nth(2, 'ABCDE') == 'C'
128143
assert nth(2, iter('ABCDE')) == 'C'

0 commit comments

Comments
 (0)