Dual look-up on keys?

Grant Edwards grante at visi.com
Wed Mar 5 18:31:45 EST 2008


On 2008-03-05, castironpi at gmail.com <castironpi at gmail.com> wrote:

> Are you vegetarian?

Some days.

> A little off topic.

Ya think?

> Anyway, if (a,b) is a key in dictionary d, can it guarantee
> that (b,a) is also in it, and maps to the same object?

Do you not know how to run the Python interpreter?

  >>> d = {(1,2): "onetwo"}
  >>> (1,2) in d
  True
  >>> (2,1) in d
  False

Tuples are ordered, so why would you expect that the tuple
(a,b) be considered equal to the tuple (b,a)?  There is, of
course, the degenerate case where a and b are the same so that
the tuple (a,b) does equal (b,a):

  >>> t = (1,2,3)
  >>> a = t 
  >>> b = t
  >>> d = {(a,b): "hi there"}
  >>> (b,a) in d
  True

An unoderded collection of objects in Python is called a set,
but sets are mutable so they're not hashable:

  >>> s1 = set((1,2))
  >>> s2 = set((2,1))
  >>> s1 == s2
  True
  >>> d = {s1: "hi there"}
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  TypeError: set objects are unhashable
  
To solve that problem, Python provides the immutable
"frozenset" type:

  >>> s1 = frozenset((1,2))
  >>> s2 = frozenset((2,1))
  >>> s1 == s2
  True
  >>> d = {s1: "hi there"}
  >>> s1 in d
  True
  >>> s2 in d
  True


See how much better a result you get when you ask an
understandble, specific, concrete question?

-- 
Grant Edwards                   grante             Yow!  Do I hear th'
                                  at               SPINNING of various
                               visi.com            WHIRRING, ROUND, and WARM
                                                   WHIRLOMATICS?!



More information about the Python-list mailing list