相关疑难解决方法(0)

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, …
Run Code Online (Sandbox Code Playgroud)

python

8
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1