[Tutor] Python dictionary element order

Lloyd Kvam pythonTutor at venix.com
Mon Apr 19 19:06:54 EDT 2004


The ordering of keys and values retrieved from a dictionary is
undefined.  There is no requirement that keys or values support an
ordering.  For instance, they could be complex numbers.


On Mon, 2004-04-19 at 18:41, tpc at csua.berkeley.edu wrote:
> hi everybody, I am confused about the default element order for keys of
> type string in Python dictionary.
> 
> <code>
> fruitlist = ['apple', 'grape', 'orange', 'pear', 'watermelon', 'mango']
> eaten = {}
> while fruitlist:
>         fruit = fruitlist.pop()
>         if fruit not in eaten:
> 		eaten[fruit] = 1
> </code>
> eaten outputs
> {'grape': 1, 'apple': 1, 'pear': 1, 'mango': 1, 'watermelon': 1, 'orange':
> 1}
> 
> When I input a list of numbers:
> 
> <code>
> numlist = [1, 2, 3, 4, 5, 6]
> numdict = {}
> while numlist:
> 	num = numlist.pop()
> 	if num not in numdict:
> 		numdict[num] = 'NULL'
> </code>
> numdict outputs
> {1: 'NULL', 2: 'NULL', 3: 'NULL', 4: 'NULL', 5: 'NULL', 6: 'NULL'}
> 
> I understand list.pop() outputs the last element in the list, so
> the dictionary element order indicated to me there was some kind of
> default sorting.  The first element in eaten should be 'mango', or at the
> very least 'apple' if Python dictionaries by default sort keys of type string
> alphabetically.
> 
> What is going on here ?
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list