循环词典

时间:2014-12-15 05:35:23

标签: python directory

我的代码:

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]

我的输出是:

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

我的问题是为什么我的输出是从" orange"而不是" banana"然后"苹果然后"橙色:然后"梨"?

3 个答案:

答案 0 :(得分:3)

Python dicts是无序的,即它们的键不在词典排序中。如果您希望始终订购密钥,请改用OrderedDict。否则,您也可以对列表进行排序,而是使用for i in sorted(prices):

答案 1 :(得分:1)

如果您需要使用订单词典,那么orderdict将非常适合您:

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)  

这给出了:

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)])

答案 2 :(得分:0)

dict在Python中没有订购。

你可以sort先键入然后再使用它们:

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

按字母顺序打印。

您还可以使用自己的自定义排序键,如:

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]

编辑:

如果您需要ordered dict,则集合库中会有一个实现。