[Tutor] outputting dictionary key/value pairs

Cliff Wells logiplex at qwest.net
Wed Aug 6 16:38:48 EDT 2003


On Fri, 2003-08-01 at 09:18, Terence Lo wrote:
> hi,
> 
>  supoose i create a dictionary of the form:
> 
> dict = {"d1": "a", "d2": "b", "d3": "c"}

Don't use dict as a variable name.  It shadows a builtin.

>>> dict
<type 'dict'>

> why is it that when i loop through the dictionary,
> 
> eg.
> 
> for k,v in dict.items():
> 	print k,v
> 
> 
> the dictionary items aren't output in the order they appear in the
> dictionary.  they seem to be returned in an arbitrary order.

It isn't arbitrary, but for all practical purposes, it might as well
be.  Dictionaries are hash-tables, which means the key (i.e. the index)
is mathematically generated in such a way to distribute the keys evenly
and avoid collisions (two keys having the same hash value).

You can try this yourself:

>>> hash
<built-in function hash>
>>> hash('a')
-468864544
>>> hash('b')
-340864157
>>> hash('c')
-212863774

As you can see, the value of the key has little to do with its relative
value after hashing.

Hashes for integers are the same as the integer (hash(100) == 100), but
that is an implementation detail and could change without warning.

Basically, in the dictionary you define above, the string "d1" is never
actually stored anywhere, rather, the hash value of the string "d1" is
used as the index.  Whenever you request dict['d1'], Python looks up
dict[hash('d1')], and returns whatever value is stored there.

You can search on Google for more information on hash tables if you
like.

> is there a quick way to loop through the dict and output the contents in
> order?  namely  d1 .. d2.. d3 ?

Not really.  You can do things like:

>>> d = {"d1": "a", "d2": "b", "d3": "c"}
>>> sorted = d.items()
>>> sorted.sort()
>>> for k, v in sorted:
...     print k, v
...
d1 a
d2 b
d3 c
>>>


Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726  (800) 735-0555




More information about the Tutor mailing list