Keeping Track Of The Procedure


#1

8.Keeping Track of The Procedure


When I run the code,why is the appearing result starting from orange
It should have started with banana instead as it is above in the input.
Can anyone help?


#2
prices = { "banana": 4, "apple": 2, "orange": 1.5,  "pear": 3 }
foodlist = ["banana","apple","orange","pear"]

for food in foodlist:
    print food
    print "price: %s" % prices[food]
banana
price: 4
apple
price: 2
orange
price: 1.5
pear
price: 3

Still a beginner myself but I believe that dictionaries don’t store key/values in any order so you would have to make a list of the order you want.


#3

Before Python 3.6, the way that the dictionary (dict) type was implemented in Python did not require that it maintain the order of the key-value pairs it contained. Codecademy’s course on Python is based on Python 2, so your dictionary objects won’t preserve order.

There is a separate object, OrderedDict, available in Python 2 which will preserve the internal order of the dictionary.

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

Hope that answers your question. :slight_smile:


#4

Thanks for replying.
My input code is same as yours.
But the obtained result at the console is different.
Why this diffference?


#5

Thanks a lot ,this really helped :slightly_smiling_face:


#6

I’m not an expert on the technical implementation details of Python, but I think that the reason you are getting a different output to @haydhn (and to anyone else who ran your code) is because when you create the dictionary, Python calculates a hash of your key names (so it hashes banana for example) and then uses the hash value rather than explicitly using banana.

If you were interested, there’s a lot to be learned from reading around the technical documentation for Python, but it is very detailled in parts.

No problem, glad I could help. :slight_smile: