Why is the output as such?


#1

This is my code:

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

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

for key in prices:
print key
print “price: %s” % prices[key]
print “stock: %s” % stock[key]

This is the output:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

Shouldn’t the order be banana, apple,orange and then pear AND not
orange, pear,banana, apple??


#2

why should it? Dictionaries are unordered by nature given they are accessed by key, they don’t have to be ordered.


#3

so is there anyway to print the dictionary exactly the way i made it?


#4

Why would you want it?

Yes, it does exist in python. Python has collections, which also contains a ordered dictionary.


#6

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