Finding the difference between two complex dictionaries
I have two dictionaries with 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 a given difference between each key in a dictionary, that is, dict1 ['a'] - dict2 ['a'] should return [3,4]. Any thought is appreciated.
source to share
You have the wrong data structure for what you are trying to do.
Use this instead.
dict1 = {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
dict2 = {'a': [(1, 2), (5, 6)], 'b': [(1, 2), (7, 8)]}
Life is easier when you are trying to perform given operations on immutable objects like tuples.
This will convert a list of lists to a list of tuples.
>>> dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
{'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
Here's a complete solution.
>>> dict1t= dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
>>> dict2t= dict( (key,[tuple(v) for v in dict2[key]]) for key in dict2 )
>>> set(dict1t['a'])-set(dict2t['a'])
set([(3, 4)])
source to share
Using modified elements (like lists) makes the problem more difficult because it eliminates the simple use of a Python data structure set
. It might be worth making temporary copies / versions that actually use tuples instead of these 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 an actual difference in settings, not a symmetrical difference, etc. Of course, you can return tuples in lists before returning, and depending on your exact requirements.
source to share
applicable to list or dict or number when a and b have the same structure
c={'a':'1','b':'2'}
d={'a':'10','b':'20'}
e={'x':c,'t':15}
f={'x':d,'t':19}
def diff(a,b):
if isinstance(a, int) and isinstance(b, int):
b = b - a
return b
if isinstance(a, str) and isinstance(b, str):
if a.isdigit() and b.isdigit():
b = str(int(b) - int(a))
return b
else:
b = a
return b
if type(a) is list and type(b) is list:
for i in range(len(a)):
b[i] = diff(a[i],b[i])
return b
if type(a) is dict and type(b) is dict:
for k,v in b.iteritems():
b[k] = diff(a[k],b[k])
return b
print diff(e,f)
source to share