如何遍历字典

15 投票
3 回答
24065 浏览
提问于 2025-04-17 08:46
In [1]: test = {}

In [2]: test["apple"] = "green"

In [3]: test["banana"] = "yellow"

In [4]: test["orange"] = "orange"

In [5]: for fruit, colour in test:
   ....:     print(fruit)
   ....:     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-8930fa4ae2ac> in <module>()
----> 1 for fruit, colour in test:
      2     print(fruit)
      3 

ValueError: too many values to unpack

我想要做的是遍历 test,同时获取键和值。如果我只是用 for item in test:,我只能得到键。

最终想要的结果示例如下:

for fruit, colour in test:
    print(f"The fruit {fruit} is the colour {colour}")

3 个回答

4

正常情况下,for key in mydict 是用来遍历字典中的键的。如果你想遍历字典中的项(键值对),可以使用下面的方式:

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

更改

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 可以返回一个包含 键值对元组列表,或者返回一个可以遍历 键和值迭代器

另外,你也可以通过键来访问值,像下面这个例子一样:

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

使用 items() 方法可以从 test 中获取一个包含 (键, 值) 对的可迭代对象:

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

这个内容在 教程 中有介绍。

在 Python 2 中,items 会返回一个具体的键值对列表;如果你想要一个懒加载的可迭代对象,可以使用 iteritems

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

撰写回答