Crossing vocabulary

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 is my output printed from "orange" and not "banana" and then "apple" then "orange": then "pear"?

+3


source to share


3 answers


Python dicts are unordered, meaning their keys are not in lexicographic sort. If you want the keys to be always ordered, use instead OrderedDict

. Otherwise, you can also sort the list and use instead for i in sorted(prices):

.



+2


source


dict

in Python are not ordered.

You can sort first open them and then use them:

for i in sorted(prices): # sorts the keys
    print i
    print "price : %s" % prices[i]
    print "stock : %s" % stock[i]

      

Print in alphabetical order.



You can also use your own custom sort key, for example:

for i in sorted(prices, key=str.lower): # sorts the keys disregarding case
    print i
    print "price : %s" % prices[i]
    print "stock : %s" % stock[i]

      

Edit:

If you need an order dict , there is an implementation in the collections library.

+1


source


If you need to work with order dictionaries, orderdict is perfect for you:

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

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

from collections import OrderedDict
from operator import itemgetter

prices1 = OrderedDict(sorted(prices.items(), key = itemgetter(0)))
stock1  = OrderedDict(sorted(stock.items() , key = itemgetter(0)))

#print(list(prices1.keys()))

for i in prices1:
    print(i)
    print("price : %s" % prices1[i])
    print("stock : %s" % stock1[i])

print(prices1)    
print(stock1)  

      

This gives:

apple
price : 2
stock : 0
banana
price : 4
stock : 6
orange
price : 1.5
stock : 32
pear
price : 3
stock : 15
OrderedDict([('apple', 2), ('banana', 4), ('orange', 1.5), ('pear', 3)])
OrderedDict([('apple', 0), ('banana', 6), ('orange', 32), ('pear', 15)])

      

+1


source







All Articles