[Tutor] Python dictionary element order

tpc at csua.berkeley.edu tpc at csua.berkeley.edu
Mon Apr 19 18:41:54 EDT 2004

hi everybody, I am confused about the default element order for keys of
type string in Python dictionary.

fruitlist = ['apple', 'grape', 'orange', 'pear', 'watermelon', 'mango']
eaten = {}
while fruitlist:
        fruit = fruitlist.pop()
        if fruit not in eaten:
		eaten[fruit] = 1
eaten outputs
{'grape': 1, 'apple': 1, 'pear': 1, 'mango': 1, 'watermelon': 1, 'orange':

When I input a list of numbers:

numlist = [1, 2, 3, 4, 5, 6]
numdict = {}
while numlist:
	num = numlist.pop()
	if num not in numdict:
		numdict[num] = 'NULL'
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

What is going on here ?

More information about the Tutor mailing list