dictionnaries and lookup tables

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Oct 11 19:14:01 EDT 2005


On Tue, 11 Oct 2005 11:50:24 -0700, m.barenco wrote:

> Just to build up on that, when I run:
> 
> #start of listing
> import random
> 
> A={1:None,2:None,"hello":None,(1,2,3):None}
> 
> def dictcomp(n):
> 	for i in range(n):
> 		B=A.copy()
> 		C=A.copy()
> 		b=random.uniform(0,1)
> 		c=random.uniform(0,1)
> 		B[b]=None
> 		C[c]=None
> 		res=((B>C)==(b>c))
> 		print res,
> 
> dictcomp(1000)
> #end of listing
> 
> I get 1000 True's on the output, which suggests that key-wise ordering
> is implemented in some guise. The question is: how do I access that?

I don't think your code is showing what you think it is showing. I think
you have discovered an accidental invariant that depends on the *specific*
details of your code. In fact, I predict that if you run that code again,
you will randomly get 1000 Trues, or 1000 Falses, but never mixed Trues
and Falses.

Does this quote from the Python reference manual help you?

"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary's
history of insertions and deletions."

http://docs.python.org/lib/typesmapping.html



What about this?

"Mappings (dictionaries) compare equal if and only if their sorted (key,
value) lists compare equal. Outcomes other than equality are resolved
consistently, but are not otherwise defined."

http://docs.python.org/ref/comparisons.html


In other words, even if you have discovered a consistent invariant
of dict behaviour, you can't rely on it -- it may disappear with the next
release of Python, or if you use an older version, or a version on a
different platform, or even because you've deleted an item from a dict and
then put it back in. (And if you know anything about typical
implementations of hash tables, you will understand why that last one is
quite reasonable.)




-- 
Steven.




More information about the Python-list mailing list