different key, same value in dictionaries

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Feb 9 17:20:42 EST 2008


On Sat, 09 Feb 2008 13:51:34 -0800, Magdoll wrote:

> Is there a cleaner way to do this example:
> 
> d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30}
> 
> The key is always a pair (x,y), but d[(x,y)] should have the same result
> as d[(y,x)]. So either I would have to store both d[(x,y)] and d[(y,x)]
> (unncessary extra space?)

Worse than the extra space is the near certainty of d[(x,y)] and d[(y,x)] 
getting out of sync.


> or write something like:
> 
> if x <= y: return d[(x,y)]
> else:       return d[(y,x)]

Arggh, scattering all those tests throughout your code is too much like 
hard work!

 
> I'm not familiar with python enough, so I want to know whether these are
> my only choices....

Oh no. Here's a good one:


class PairDict(dict):
    def __getitem__(self, key):
        if key[1] < key[0]: key = (key[1], key[0])
        return super(PairDict, self).__getitem__(key)


and here it is in use:

>>> d = PairDict([((1,2), 5), ((3,4), 10)])
>>> d[(1,2)]
5
>>> d[(2,1)]
5



-- 
Steven



More information about the Python-list mailing list