My Code :
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6,"apple": 0,"orange": 32,"pear": 15,}
for i in prices:
print i
print "price : %s" % prices[i]
print "stock : %s" % stock[i]
My Output is:
orange
price : 1.5
stock : 32
pear
price : 3
stock : 15
banana
price : 4
stock : 6
apple
price : 2
stock : 0
None
My question is why my output is printed from "orange" rather than "banana " then "apple then "orange: then "pear"?
Python dicts are unordered, that is their keys are not in lexicographical sorting. If you want the keys to be always ordered, use an OrderedDict instead. Otherwise, you can also sort the list and instead use for i in sorted(prices):.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With