gpt4 book ai didi

python - 如何遍历字典

转载 作者:太空狗 更新时间:2023-10-29 20:32:55 25 4
gpt4 key购买 nike

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: 我只得到 key 。

最终目标的一个例子是:

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

最佳答案

在 Python 2 中你会这样做:

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

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

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

这包含在 the tutorial 中.

关于python - 如何遍历字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8589812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com