Python迭代字典

jdb*_*org 8 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
Run Code Online (Sandbox Code Playgroud)

我想要的是迭代测试并获得密钥和值.如果我只是做一个for item in test:我只得到钥匙.

最终目标的一个例子是:

for fruit, colour in test:
    print "The fruit %s is the colour %s" % (fruit, colour)
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 18

在Python 2中你会做:

for fruit, color in test.iteritems():
    # do stuff
Run Code Online (Sandbox Code Playgroud)

在Python 3中,items()改为使用(iteritems()已被删除):

for fruit, color in test.items():
    # do stuff
Run Code Online (Sandbox Code Playgroud)

教程将介绍这一点.


Abh*_*jit 12

更改

for fruit, colour in test:
    print "The fruit %s is the colour %s" % (fruit, colour)
Run Code Online (Sandbox Code Playgroud)

for fruit, colour in test.items():
    print "The fruit %s is the colour %s" % (fruit, colour)
Run Code Online (Sandbox Code Playgroud)

要么

for fruit, colour in test.iteritems():
    print "The fruit %s is the colour %s" % (fruit, colour)
Run Code Online (Sandbox Code Playgroud)

通常情况下,如果你遍历一个字典,它只会返回一个键,所以这就是它错误地说"解压缩的值太多"的原因.相反,items或者iteritems将返回list of tupleskey value pairiterator遍历key and values.

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

for fruit in test:
    print "The fruit %s is the colour %s" % (fruit, test[fruit])
Run Code Online (Sandbox Code Playgroud)