2011-12-21 173 views
5
In [26]: test = {} 

In [27]: test["apple"] = "green" 

In [28]: test["banana"] = "yellow" 

In [29]: test["orange"] = "orange" 

In [32]: for fruit, colour in test: 
    ....:  print fruit 
    ....:  
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
/home1/users/joe.borg/<ipython-input-32-8930fa4ae2ac> in <module>() 
----> 1 for fruit, colour in test: 
     2  print fruit 
     3 

ValueError: too many values to unpack 

我想要的是迭代測試並將鍵和值合在一起。如果我只是做一個for item in test:我只能得到鑰匙。Python遍歷字典

的最終目標的一個例子是:

for fruit, colour in test: 
    print "The fruit %s is the colour %s" % (fruit, colour) 
+6

看到'幫助(字典)' – u0b34a0f6ae 2011-12-21 12:29:32

+0

爲什麼不'在測試的水果:打印「果實%s是顏色% s「%(水果,測試[水果])'? – mtrw 2011-12-21 12:32:28

回答

13

在Python 2,你會怎麼做:

for fruit, color in test.iteritems(): 
    # do stuff 

在Python 3,使用items()代替(iteritems()已被刪除):

for fruit, color in test.items(): 
    # do stuff 

這包括在the tutorial

+1

在Python 3中,您必須將'iterator()'改爲'item()''才能在test.items()中使用水果顏色,因爲dict.iteritems()已被移除,現在dict.items()同樣的東西 – 2017-09-09 15:55:45

+0

@ user-asterix謝謝,我已經更新了答案,以澄清這一點。 – 2017-09-11 07:21:47

4

正常的for key in mydict在密鑰上迭代。你想重複的項目:

for fruit, colour in test.iteritems(): 
    print "The fruit %s is the colour %s" % (fruit, colour) 
12

變化

for fruit, colour in test: 
    print "The fruit %s is the colour %s" % (fruit, colour) 

for fruit, colour in test.items(): 
    print "The fruit %s is the colour %s" % (fruit, colour) 

for fruit, colour in test.iteritems(): 
    print "The fruit %s is the colour %s" % (fruit, colour) 

通常情況下,如果你遍歷一本字典它只會返回一個關鍵,所以這是它犯錯的原因或者說 - 「解壓縮的值太多」。 而是itemsiteritems將返回list of tupleskey value pairiterator以迭代key and values

或者你可以隨時通過鍵訪問值如下面的例子

for fruit in test: 
    print "The fruit %s is the colour %s" % (fruit, test[fruit])