使用 .iteritems() 迭代 Python 字典中的键、值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30223099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:05:58  来源:igfitidea点击:

Using .iteritems() to iterate over key, value in Python dictionary

pythonpython-2.7dictionary

提问by AdjunctProfessorFalcon

Note: I have read this post and Alex Martelli's response, but I don't really/fully understand his answer. It's a bit beyond my current understanding. I would like help understanding it better.

注意:我已经阅读了这篇文章和 Alex Martelli 的回复,但我并没有真正/完全理解他的回答。这有点超出我目前的理解。我想帮助更好地理解它。

I understand that when you try the following for loop:

我知道当您尝试以下 for 循环时:

for key, value in dict:
    print key
    print value 

you get:

你得到:

ValueError: too many values to unpack

Although you can loop over a dictionary and just get the keys with the following:

尽管您可以遍历字典并使用以下内容获取键:

for key in dict:
    print key 

Can anyone provide a slightly less-advanced explanation for why you cannot iterate over a dictionary using key, value without using .iteritems()?

任何人都可以提供一个稍微不那么高级的解释为什么你不能使用 key, value 迭代字典而不使用.iteritems()

采纳答案by Stefan Pochmann

The other answer explains it well. But here are some further illustrations for how it behaves, by showing cases where it actually works without error (so you can see something):

另一个答案很好地解释了它。但是这里有一些关于它的行为方式的进一步说明,通过展示它实际工作而没有错误的情况(所以你可以看到一些东西):

>>> d = {(1,2): 3, (4,5): 6}
>>> for k, v in d:
        print k, v

1 2
4 5

The loop goes through the keys (1,2)and (4,5)and since those "happen to be" tuples of size 2, they can be assigned to kand v.

循环遍历键(1,2)(4,5)并且由于那些“恰好是”大小为 2 的元组,因此可以将它们分配给kv

Works with strings as well, as long as they have exactly two characters:

也适用于字符串,只要它们正好有两个字符:

>>> d = {"AB":3, "CD":6}
>>> for k, v in d:
        print k, v

A B
C D

I assume in your case it was something like this?

我假设在你的情况下是这样的?

>>> d = {"ABC":3, "CD":6}
>>> for k, v in d:
        print k, v

Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    for k, v in d:
ValueError: too many values to unpack

Here, the key "ABC" is a triple and thus Python complains about trying to unpack it into just two variables.

在这里,键 "ABC" 是一个三元组,因此 Python 抱怨试图将其解包为两个变量。

回答by user2357112 supports Monica

Python has a feature called iterable unpacking. When you do

Python 有一个称为可迭代解包的功能。当你做

a, b = thing

Python assumes thingis a tuple or list or something with 2 items, and it assigns the first and second items to aand b. This also works in a forloop:

Python 假设thing是一个元组或列表或具有 2 个项目的东西,并将第一项和第二项分配给ab。这也适用于for循环:

for a, b in thing:

is equivalent to

相当于

for c in thing:
    a, b = c

except it doesn't create that cvariable.

除了它不创建该c变量。

This means that if you do

这意味着如果你这样做

for k, v in d:

Python can't look at the fact that you've said k, vinstead of kand give you items instead of keys, because maybe the keys are 2-tuples. It has to iterate over the keys and try to unpack each key into the kand vvariables.

Python 无法查看您所说的k, v而不是k给您项目而不是键的事实,因为键可能是 2 元组。它必须遍历键并尝试将每个键解包到kv变量中。

回答by seven7e

While using for xx in XX, you are actually using an iterator to iterates the XX, and XX must be iterable. You can use iterfunction to get an iterator, as

在使用 时for xx in XX,您实际上是在使用迭代器来迭代 XX,而 XX 必须是可迭代的。您可以使用iter函数来获取迭代器,如

>>> d = dict(a=1,b=2)
>>> i = iter(d)
>>> i
<dictionary-keyiterator object at 0x6ffff8739f0>

and using nextto access the elements.

next用于访问元素。

>>> next(i)
'a'

So in every iteration of for k in d, kwill be assigned to next(i), and it's only the key without value. e.g., in the first round of iteration,

所以在 的每一次迭代中for k in dk都会被赋值给next(i),并且它只是没有值的键。例如,在第一轮迭代中,

k = 'a'

While .iteritems()will return another iterator with can get a tuple of key-value combined. Let's check this

While.iteritems()将返回另一个迭代器,可以得到一个键值组合的元组。让我们检查一下

>>> i = d.iteritems()
>>> i
<dictionary-itemiterator object at 0x6ffff873998>
>>> next(i)
('a', 1)

See? In the first round of for k, v in d.iteritems(), we actually get this assignment

看?在第一轮for k, v in d.iteritems(),我们实际上得到了这个任务

k, v = ('a', 1)

Thus, if you using for k, v in d, you will get

因此,如果您使用for k, v in d,您将获得

k, v = 'a'

That's an illegal assignment.

那是非法委托。

回答by nerdfiles

In Python 2.7.6 it seems that you may want to check for subproperties of the dictionary with dict.has_key(property_name).

在 Python 2.7.6 中,您似乎想用dict.has_key(property_name).