Query regarding order of a dictionary


#1

I WROTE THIS CODE:

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[“Pasta”] = 10
menu[“Tiramisu Shake”] = 5.75
menu[“Chicken Tikka”] = 7.50

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

THIS WAS THE RESULT:

14.5
There are 4 items on the menu.
{‘Pasta’: 10, ‘Chicken Alfredo’: 14.5, ‘Tiramisu Shake’: 5.75, ‘Chicken Tikka’: 7.5}

I added the 3 items - Pasta, Tiramisu Shake and Chicken Tikka.
Why were my items given the numbers 1, 3 and 4 ?
Shouldn’t it have been 2, 3 and 4 ?


#2

Why would dictionaries need to be ordered?

they are accessed by key, lists are accessed by index, as such, lists need to be ordered. Dictionaries do not need to be ordered.


#3

So when I would add key/value pair to a dictionary, it would get added in any random order?
Or may be it does not matter in which order they get added? Because we will obviously access it by the key.


#4

to understand the order, you would need to understanding the underlying hash table and its implementation within the python language

it doesn’t matter in most cases, if however you have a case where it does matter, you will need to find a way to make the dictionary ordered, thankfully python offers this;

https://docs.python.org/2/library/collections.html#collections.OrderedDict

But then you have to be careful about the advantages and disadvantages of each approach, and ask yourself if dictionaries is even the way to go


#5

They’re not stored in order, not any order at all, dict’s provide lookup by key

Which order they then “come out” in varies with implementation and possibly changes between runs as well - if something isn’t defined, that means you shouldn’t rely on it, it could be anything.

(python 3.7+ do keep insertion order though (it’s part of the language standard from then on))


#6

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