Getting the difference (delta) between two lists of dictionaries

user1513388 picture user1513388 · Nov 3, 2013 · Viewed 22.9k times · Source

I have the following Python data structures:

data1 = [{'name': u'String 1'}, {'name': u'String 2'}]
data2 = [{'name': u'String 1'}, {'name': u'String 2'}, {'name': u'String 3'}]

I'm looking for the best way to get the delta between the two lists. Is there anything in Python that's as convenient as the JavaScript Underscore.js (_.difference) library?

Answer

zero323 picture zero323 · Nov 3, 2013

How about this:

>>> [x for x in data2 if x not in data1]
[{'name': u'String 3'}]

Edit:

If you need symmetric difference you can use :

>>> [x for x in data1 + data2 if x not in data1 or x not in data2]

or

>>> [x for x in data1 if x not in data2] + [y for y in data2 if y not in data1]

One more edit

You can also use sets:

>>> from functools import reduce
>>> s1 = set(reduce(lambda x, y: x + y, [x.items() for x in data1]))
>>> s2 = set(reduce(lambda x, y: x + y, [x.items() for x in data2]))

>>> s2.difference(s1)
>>> s2.symmetric_difference(s1)