2011-12-21 176 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])