Q:

Create (k, v1, ..., vn) tuples based on matching dict keys

I'm using Python 2.6, and I have two datasets, each being a list of dictionaries. The two datasets look like this:
[{'foo': 3}, {'bar': 4}]
[{'bar': 1}, {'foo': 8}]

From these two datasets, I want to create a single list of tuples that would look like this for the input data: 
[('foo', 3, 8), ('bar', 4, 1)]

It is important that the number in the first dataset come first in the resulting tuple, btw. 
I've actually accomplished this through various means (including a nested list comprehension), but it seems like it should be simpler/cleaner. I was surprised that nothing in itertools jumped out at me (though I did do one implementation w/ chain that resulted in a 2-tuple where the ints were in a list). Can anyone provide a clean solution, or is there just not one? 

A:

You can use a defaultdict:
from collections import defaultdict

datasets = [{'foo': 3}, {'bar': 4}], [{'bar': 1}, {'foo': 8}]    

result = defaultdict(list)

for dataset in datasets:
    for eachdict in dataset:
        for key, value in eachdict.iteritems():
            result[key].append(value)

# the nested loops as a one-liner (utterly unnecessary):
# any(result[key].append(value) for dataset in datasets 
#                               for eachdict in dataset 
#                               for key, value in eachdict.iteritems())

# if you really need your output in exactly that format:
# result = [(key,) + tuple(values) for key, values in result.iteritems()]
print result

That seems like the cleanest approach to me.

