Unexpected order of calculation

#1

Hello

In the "A Day at the Supermarket" exercise, the following function:

prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}

stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}

total = 0

for key in prices:
total += prices[key] * stock[key]
print(total)

Gave me the following output:

48.0
93.0
117.0
117.0
117.0
None

It appears it calculated "orange" first, then "pear", then "apple" and then "banana", which is not the expected order of calculation, although the end result is the same.

In Python 3.6.1 shell, I received the correct output:

24
24
72.0
117.0

Is this a difference between Python 3 and 2, and if so, why does it calculate it in such an order in Python 2?

#2

dictionaries are by unodered by nature, since you access by key and not by index

Since python3.6 dictionaries, i will have to find the PEP which explains this

#4

to understand this, you will need to understand the implantation of dictionaries and memory allocation. Its not really worth getting into right now

for now, assumes python can handle this

#6

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