Dictionary Keys question
DustanGroups at gmail.com
Thu Jan 31 00:08:52 CET 2008
On Jan 30, 4:47 pm, FireNWater <kho... at gmail.com> wrote:
> I'm curious why the different outputs of this code. If I make the
> dictionary with letters as the keys, they are not listed in the
> dictionary in alphabetical order, but if I use the integers then the
> keys are in numerical order.
> I know that the order of the keys is not important in a dictionary,
> but I was just curious about what causes the differences. Thanks!!
> list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
> list2 = [1,2,3,4,5,6,7,8]
> Dictionary = dict(zip(list1, list2))
> print Dictionary
> Dictionary1 = dict(zip(list2, list1))
> print Dictionary1
The underlying order is a result, in part, of the key's hash codes*.
Integers are hash coded by their integer values, therefore, they
appear in numeric order. Strings, however, use an algorithm that
ensures as unique hash codes as possible. Notice the difference:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
1, 2, 3, 4, 5, 6, 7, 8])
[-468864544, -340864157, -212863774, -84863387, 43136996, 171137383,
299137766, 427138153, 1, 2, 3, 4, 5, 6, 7, 8]
* emphasis on the "in part". Other factors include the amount of
memory space available, order added, the current size of the
underlying hash table, etc.
More information about the Python-list