繁体   English   中英

Python迭代字典

[英]Python iterate over a dictionary

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)

在Python 2中你会做:

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

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

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

教程将介绍这一点。

更改

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将返回key value pair list of tuplesiterator以迭代key and values

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM