Efficient comparison of all python dict elements

I am looking for a more efficient way to compare between all python dict elements.

Here is the psuedocode of what I am doing:

for key1 in dict: for key2 in dict: if not key1 == key2: compare(key1,key2) 

if the length of dict is N, it is N ^ 2 - N. Is there any way to not repeat the elements in the second loop? For lists, this will be:

 N = len(list) for i in range(1:(N-1)): for j in range((i+1):N): compare(list[i], list[j]) 

Anyway, to do this for the dict case?

+4
source share
3 answers

Maybe something like

 >>> import itertools >>> >>> d = {1:2, 2:3, 3:4} >>> >>> for k0, k1 in itertools.combinations(d,2): ... print 'compare', k0, k1 ... compare 1 2 compare 1 3 compare 2 3 

if it doesn't matter to you whether you get (1,2) or (2,1). [Of course, you could sorted(d) over sorted(d) or some option if you would like to get a certain order, or compare both (k0, k1) and (k1, k0) if that matters.]

[BTW: do not name your list of lists or your dicts dict - which captures the built-in functions, and they are convenient to use.]

+9
source

You can use OrderedDict , and then write code similar to what you already have for lists.

Here is an example:

 from collections import OrderedDict def compare(a, b): print "compare", a, b d = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)]) for key1 in d: for key2 in reversed(d): if key1 == key2: break compare(key1, key2) 

When I run this, it prints:

 compare banana orange compare banana pear compare banana apple compare apple orange compare apple pear compare pear orange 
+3
source
 >>> equal = lambda d1, d2: all(d1.get(k) == d2.get(k) for k in set(d1.keys() + d2.keys())) >>> print equal({'a':1, 'b':2}, {'b':2, 'a':1}) True >>> print equal({'a':1, 'b':2}, {'b':2, 'a':2}) False 

This solution is quite effective: all is lasy - stops on the first False , and the generator expression is too lys too :)

 def deep_equal(d1, d2): ''' Deep comparison ''' if type(d1) != type(d2): return False if isinstance(d1, dict): return all(ddeep_equal(d1.get(k), d2.get(k)) for k in set(d1.keys() + d2.keys())) return d1 == d2 
0
source