Queries regarding printing of Dictionary after adding key value pair


Section : Python Lists and Dictionaries ::
New Entries
The problem :
Add at least three more key-value pairs to the menu variable, with the dish name (as a "string") for the key and the price (a float or integer) as the value.
My code :
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
menu['Pasta'] = 30.63
menu['Burger'] = 40.89
menu['Pizza'] = 25.52
print "There are " + str(len(menu)) + " items on the menu."
print menu

Question : The o/p is coming {'Pasta': 30.63, 'Chicken Alfredo': 14.5, 'Pizza': 25.52, 'Burger': 40.89}
The sequence of the items in the output is different to that I have added in the dictionary. Why is that?


Dictionaries are not sequential (unless we sort them for reporting, but they won't stay that way) and have strings as indices. The properties (key-value pairs) can be entered in any order, and Python can query/enumerate them in any order. Unlike lists which are ordered, dictionaries are unordered.


Is there any specific reason for that..? Obviously if it would have maintained some particular sequence, needless to say that would have been great..


SERP: why are python dictionaries not ordered?

One of the answers states: "Python dictionaries are not meant to store order, only key-value pairs."


Okay.. Thanks a lot for the reply :smile: