Python 循环字典

Python 循环字典,python,directory,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 sto

我的代码:

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”然后是“apple”然后是“orange:然后是“pear”?

Python dict是无序的,也就是说它们的键不在字典排序中。如果希望始终对密钥进行排序,请改用。否则,您也可以对列表进行排序,并在排序(价格)中为i使用

dict
Python中的s未排序

您可以先使用这些密钥,然后再使用它们:

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]
编辑:
如果您需要,集合库中有一个实现。

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

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

在我的示例中,我的理解是:对于第一个循环打印,我等于打印香蕉打印“价格:%s”%prices[i]等于prices[banana]#关键“香蕉”库存的值[i]等于库存[banana]这种理解是否错误?@Govindchouhan是正确的。当您在字典上迭代时,基本上就是在它的
键上迭代。由于两个dict中的键相同,您可以使用
dictionary[key]
轻松访问这些值。我希望它以存储目录值的相同顺序打印目录值,使用sorted将按字母顺序打印。