Keeping Track Of The Procedure


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?

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]
price: 4
price: 2
price: 1.5
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.


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.

Hope that answers your question. :slight_smile:


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


Thanks a lot ,this really helped :slightly_smiling_face:


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:


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