Keeping Track of the Produce (Confusing Output)


#1

Printing each item along with its price and stock shows the order: orange, pear, banana, apple every time the code is being run, though they are in the order: banana, apple, orange, pear in the dictionary. Why does it look so?


#2

Hi @rubelchy,

Python 2 dictionaries are considered unordered, so the output might not be sorted in alphabetical order and might not appear in the order in which you originally specified the items in the dictionary.

If you want to control the order of processing of the items, you can use a list of the keys to do it.


#3

I made the code run for several times. Every time the output followed no other but the order I mentioned. That’s why I am confused.


#4

cpython 3.6 uses a different implementation of dict which has the nice property of keeping insertion order to some degree but I think that might get lost once other operations are made
still unordered, and other implementations of python3.6 might not have dicts like this - it’s not in the language specification

yeah-kind-of-difficult-to-explain-and-too-advanced, it’s just that they should all be considered unordered and then they may or may not retain order but definitely don’t rely on it


#5

Yeah the order remains the same because it’s not random, it isn’t getting shuffled, there’s an algorithm doing the ordering, and it’s deterministic (will do the very same thing each time it is executed), but which exact order that is can and will vary between python versions, even minor ones - and as mentioned, if you want order you’d use a list or an OrderedDict which does keep insertion order


#6

The Python interpreter uses what is called a hash table to keep track of storage of the items in the dictionary.

I see that @ionatan is typing a reply that contains some useful information.


#9

Tons of thanks to you both. @ionatan Can you refer me an OrderedDict? I’ve not learnt about it yet. :frowning:


#10
from collections import OrderedDict

my_dict = OrderedDict()
# my_dict is now a dictionary, it just behaves a bit differently (keeps
# insertion order) operations are still written the very same way, it's just
# its internals that are different

my_dict[4] = 2
my_dict[2] = 3
print(list(my_dict.items()))  # [(4, 2), (2, 3)]

It’s not all that commonly used though. If you’re using a dict, it most likely isn’t for the sake of tracking order of things.


#11

Thanks again. I think I’ve got my answer. Well explained by you.


#12

All of the above is worthy of study, and may come in handy in particular circumstances.

Among many possibilities, here’s one example of management of the order of output from a couple of dictionaries, taken from the current exercise …

for key in sorted(prices.keys()):
  print key
  print "price: %d" % prices[key]
  print "stock: %d" % stock[key]

#13

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