11/14 New Entries - By what criteria are the key-value pairs sorted when entered into the dictionary?


Code is:

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['1'] = 0
menu['2'] = 0
menu['3'] = 0
menu['4'] = 0
menu['5'] = 0
menu['6'] = 0
menu['7'] = 0
menu['8'] = 0
menu['9'] = 0
menu['10'] = 0
menu['11'] = 0
menu['12'] = 0
menu['13'] = 0
menu['14'] = 0
print "There are " + str(len(menu)) + " items on the menu."
print menu

And output is:

There are 15 items on the menu.
{'11': 0, 'Chicken Alfredo': 14.5, '13': 0, '12': 0, '14': 0, '10': 0, '1': 0, '3': 0, '2': 0, '5': 0, '4': 0, '7': 0, '6': 0, '9': 0, '8': 0}



The code is simple here is what i put you can copy it if you want
menu['Spam'] = 2.50
print menu['Spam']

print "There are " + str(len(menu)) + " items on the menu."
menu['Steak'] = 2.1
print menu['Steak']
menu['Fish'] = 2.1
print menu['Fish']
The are no indents
Good Luck on further codes


Sorry if I'm being dense, but that doesn't explain by what criteria are the key-value pairs sorted when entered into the dictionary, does it?


Hi @coto_i ,

A Python dictionary is an example of a hash table. The Python interpreter applies an algorithm, called a hash function, to each key, in order to compute an index for it. That index is used to place each key-value pair into a bucket, which is a list of key-value pairs that all have the same index. There or lots of buckets. The hash function is designed to make it likely that the key-value pairs will be fairly evenly spread out among the different buckets. This maximizes the efficiency of storage and retrieval.


Thank you @appylpye

As I see this is pretty advanced topic (googled a bit too some keywords taken from your answer). I was not expecting it to be easy, but it definitely goes well beyond my current knowledge. However, I do understand now why, for example, even the elements in the dictionary seem to be sorted in a "random order", it is exactly the same "random order" every time I try with the same pairs (perhaps even with different pairs?), no matter the order in which I enter said pairs into the dictionary and no matter what the dictionary already contains (I played a bit before asking here). This gives rise to more questions of course, but I guess I will dig again into this topic when I'll be more advanced. For now thank you, very helpful. :smile: