>>> mysets = (set(x.items()) for x in MyList) >>> reduce(lambda a,b: a.intersection(b), mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])
First, I created a generator that converts a list of dicts into an iterable sequence of sets of key pairs, values. You can use list comprehension here, but this method does not convert your entire list into another list, useful if you donโt know how big it will be.
Then I used a shorthand to apply a function that finds common values โโbetween each set. He finds the intersection of set 1 and set 2, which is itself a set, then the intersection of this set and set 3, etc. The mysets generator will happily serve each set as required by the reduction function until it is complete.
I believe the shortcut was deprecated as built-in in Python 3.0, but should still be available in functools.
Of course, you could make it one liner, replacing the mysets in the abbreviation with the expression of the generator, but this will reduce the readability of the IMO. In practice, I will probably even take one more step and break the lambda in my line:
>>> mysets = (set(x.items()) for x in MyList) >>> find_common = lambda a,b: a.intersection(b) >>> reduce(find_common, mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])
And if you want the end result to be a dict, just wrap it like this:
>>> dict(reduce(find_common, mysets)) {'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'}
dict can accept any iterator of keys, pairs of values, for example, a set of tuples returned at the end.