Python迭代字典

时间:2011-12-21 12:26:40

标签: python

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:我只得到密钥。

最终目标的一个例子是:

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

3 个答案:

答案 0 :(得分:17)

在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 :(得分: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 tuples key value pairiterator来迭代key and values

或者,您始终可以通过键访问该值,如以下示例所示

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

答案 2 :(得分:4)

正常for key in mydict遍历键。您想迭代项目:

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