Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient comparison of all elements of python dict

I am looking for a more efficient way to do comparisons between all elements of a python dict.

Here is 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 the dict is N, this is N^2 - N. Is there any way of not repeating the elements in the second loop? For lists, this would 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?

like image 320
user1462620 Avatar asked Dec 16 '22 22:12

user1462620


1 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 you don't care about whether you get (1,2) or (2,1). [Of course you could iterate over sorted(d) or some variant if you wanted a particular order, or compare both (k0, k1) and (k1, k0) if that mattered.]

[BTW: don't call your lists list or your dicts dict-- that clobbers the builtins, and they're handy to have around.]

like image 105
DSM Avatar answered Jan 13 '23 11:01

DSM