简体   繁体   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

What I want is to iterate over test and get the key and value together. 我想要的是迭代测试并获得密钥和值。 If I just do a for item in test: I get the key only. 如果我只是for item in test:我只获得密钥。

An example of the end goal would be: 最终目标的一个例子是:

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

In Python 2 you'd do: 在Python 2中你会做:

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

In Python 3, use items() instead ( iteritems() has been removed): 在Python 3中,使用items()代替( iteritems()已被删除):

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

This is covered in the tutorial . 教程将介绍这一点。

Change 更改

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

to

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

or 要么

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

Normally, if you iterate over a dictionary it will only return a key, so that was the reason it error-ed out saying "Too many values to unpack". 通常情况下,如果你遍历一个字典,它只会返回一个键,所以这就是它错误地说“解压缩的值太多”的原因。 Instead items or iteritems would return a list of tuples of key value pair or an iterator to iterate over the key and values . 相反, itemsiteritems将返回key value pair list of tuplesiterator以迭代key and values

Alternatively you can always access the value via key as in the following example 或者,您始终可以通过键访问该值,如以下示例所示

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

The normal for key in mydict iterates over keys. for key in mydict遍历键。 You want to iterate items: 您想要迭代项目:

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