Random Question RE: Dictionary


#1

My solution worked and everything. I’m just curious as to how python ordered the items in the dictionary and what caused the items to be random:

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

menu[‘spaghetti’] = 9
menu[‘liver & onion’] = 5.79
menu[‘prarie oysters’] = 10.99

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

and the output became:

14.5
There are 4 items on the menu.
{‘prarie oysters’: 10.99, ‘Chicken Alfredo’: 14.5, ‘liver & onion’: 5.79, ‘spaghetti’: 9}

I don’t see any discernible order in that listing, and I’m just curious about it…thoughts?


#2

to understand dictionary order, you would need to understand how dictionaries are implemented. Not really worth it to learn, what is important is understanding that dictionaries are accessed by key (not index, like list), so there is no reason for dictionaries to be ordered.


#3

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