Is my dictionary{DRUNK}?


The printed list sorts differently then the 'line order' of them being entered into the dictionary. No errors generated, but results not as expected.

There are 4 items on the menu.
{'Chicken Alfredo': 14.5, 'Fries': 4.99, 'Poutine': 9.99, 'Salad': 12.99}

I'm curious as to the 'why', for no good reason. :slight_smile:

menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
#print menu['Chicken Alfredo']

# Your code here: Add some dish-price pairs to menu!
menu['Fries'] = 4.99
menu['Poutine'] = 9.99 
menu['Salad'] = 12.99

print "There are " + str(len(menu)) + " items on the menu."
print menu


What has it promised to do differently from what you're seeing?

The case here is likely that you've got assumptions or expectations which you aren't going to be able to motivate. Seeing something unexpected should not be surprising if you have no reason to expect something else

Computers do exactly as told, so it's very important that we keep assumptions and facts strictly separate. Computers won't correct them like humans sometimes will, often without even noticing that correction


I came here with the same question as the OP - why is the print of the dictionary "jumbled" up? Thinking like a computer (i.e., doing exactly as told), I would assume that it either printed the items in the line order, or sorted them by some logic (value, alphabetical, etc.). I just can't figure out that logic (if it exists), and I have to revise my understanding of how computers work if it really is random. So I'm very interested if you or anyone can enlighten me :slight_smile:


Python does not define the order of key iteration. The dictionary is free to do it any way it pleases, including using a different order on Tuesdays.


What comes with the lack of promise is that the implementation is free to do whatever it thinks is best.
As far as python is concerned there's no "why" simply because it's not part of the language specification.

One could look up how dictionaries may be implemented. One way is to sort them, like we'd do with a paper-version. There are more clever schemes though, which allow for computing the location of the value from the key and thus eliminate searching/comparing.


Thanks for your attempt at being helpful.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.