jensph jensph - 3 days ago 5
Python Question

Compare a dictionary to itself in Python

I'd like to compare a Python dictionary with itself. For example:

for key1 in d:
for key2 in d:
if key1 == key2:
continue
compare(d[key1],d[key2])


The above would work except I'm comparing key1 with key 2 and then later the reverse (key2 with key1). The range of the second for-loop should really start after key1 to avoid repeated comparisons. How can that be done?

Answer

I think that itertools.combinations would be helpful here

>>> import itertools
>>> d = dict.fromkeys(range(5),0)
>>> list(itertools.combinations(d,2))
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

so, for your case, you'd want:

for key1,key2 in itertools.combinations(d,2):
    compare(d[key1],d[key2])

Here's a silly example where I construct a list of pairs of people with brown eyes (or hair I suppose ...):

>>> d = dict.fromkeys(["Jon","Jane","Bob","Jim","Janice"],"blue")
>>> d["Jim"] = "Brown"
>>> d["Jane"] = "Brown"
>>> d["Bob"] = "Brown"
>>> [ (x,y) for (x,y) in itertools.combinations(d,2) if d[x]=="Brown" and d[y]=="Brown" ]
[('Jane', 'Bob'), ('Jane', 'Jim'), ('Bob', 'Jim')]
Comments