Question: I have some scala futures. I can easily run them in parallel with `Future.sequence`. I can also run them one-after-another with something like this:

```
def serFut[A, B](l: Iterable[A])(fn: A ⇒ Future[B]) : Future[List[B]] =
  l.foldLeft(Future(List.empty[B])) {
    (previousFuture, next) ⇒
      for {
        previousResults ← previousFuture
        next ← fn(next)
      } yield previousResults :+ next
  }

```

(Described [here](http://www.michaelpollmeier.com/execute-scala-futures-in-serial-one-after-the-other-non-blocking/)). Now suppose that I want to run them *slightly* in parallel - ie with the constraint that at most `m` of them are running at once. The above code does this for the special case of `m=1`. Is there a nice scala-idiomatic way of doing it for general `m`? Then for extra utility, what's the most elegant way to implement a kill-switch into the routine? And could I change `m` on the fly?

My own solutions to this keep leading me back to procedural code, which feels rather wimpy next to scala elegance.

Answer: 
My approach is to sort the the combined list by the *key*, which is keys `a` + `b`. After that, for each group of dictionaries with similar key, combine them:

```
from itertools import groupby

def ab_key(dic):
    return dic['a'], dic['b']

def combine_lists_of_dicts(list_of_dic1, list_of_dic2, keyfunc):
    for key, dic_of_same_key in groupby(sorted(list_of_dic1 + list_of_dic2, key=keyfunc), keyfunc):
        combined_dic = {}
        for dic in dic_of_same_key:
            combined_dic.update(dic)
        yield combined_dic

l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]

for dic in combine_lists_of_dicts(l1, l2, ab_key):
    print dic

```

Discussion
==========

* The function `ab_key` returns a tuple of value for key `a` and `b`, used for sorting a groupping
* The `groupby` function groups all the dictionaries with similar keys together
* This solution is less efficient than that of John La Rooy, but should work fine for small lists
One can achieve a nice and quick solution using pandas.

```
l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]

import pandas as pd
pd.DataFrame(l1).merge(pd.DataFrame(l2), on=['a','b']).to_dict('records')

```