如何将键值对减少到键和值列表?

让我们假设,我在Spark中有一个键值对,如下所示.

[ (Key1, Value1), (Key1, Value2), (Key1, Vaue3), (Key2, Value4), (Key2, Value5) ]

现在我想减少这个,就像这样.

[ (Key1, [Value1, Value2, Value3]), (Key2, [Value4, Value5]) ]

也就是说,从Key-Value到Key-List of Values.

我如何使用map和reduce函数在python或scala中做到这一点?

最佳答案 collections.defaultdict可以是解决方案
https://docs.python.org/2/library/collections.html#collections.defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for key, value in [('Key1', 'Value1'), ('Key1', 'Value2'), ('Key1', 'Vaue3'), ('Key2', 'Value4'), ('Key2', 'Value5') ]:
...     d[key].append(value)

>>> print d.items()
[('Key2', ['Value4', 'Value5']), ('Key1', [ 'Value1','Value2', 'Vaue3'])]
点赞