Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding set difference between two complex dictionaries

I have two dictionaries of the following structure:

a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]}
b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]}

I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.

like image 766
Prabhu Avatar asked Apr 09 '26 11:04

Prabhu


2 Answers

The use of mutable items (such as lists) makes the problem MUCH harder, as it precludes the simple use of Python's set data structure. It may be worth making temporary copies/versions which actually use tuples in lieu of those pesky lists:

def tempaux(d):
  return dict((k, set(tuple(x) for x in v))
              for k, v in d.iteritems())

Now:

def thedifs(dd1, dd2)
  d1 = tempaux(dd1)
  d2 = tempaux(dd2)
  allkeys = set(d1).update(d2)
  empty = set()
  difs = []
  for k in allkeys:
    s1 = d1.get(k, empty)
    s2 = d2.get(k, empty)
    adif = s1 - s2
    if adif: difs.append(adif)
  return difs

This assumes actual set difference rather than symmetric difference etc. You can of course turn back the tuples into lists before returns, &c, depending on your exact requirements.

like image 136
Alex Martelli Avatar answered Apr 11 '26 00:04

Alex Martelli


>>> s1 = set([(1,2), (3,4)])
>>> s2 = set([(1,2), (5,6)])
>>> s1 - s2
{(3, 4)}
like image 23
Vinay Sajip Avatar answered Apr 11 '26 01:04

Vinay Sajip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!