Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over dictionary

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"?

like image 268
Govind chouhan Avatar asked Mar 25 '26 07:03

Govind chouhan


1 Answers

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):.

like image 104
Anshul Goyal Avatar answered Mar 27 '26 21:03

Anshul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!