使用.iteritems()在Python字典中遍历键值

时间:2021-02-15 22:24:50

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()来迭代字典。

4 个解决方案

#1


10  

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 k and v.

循环通过键(1,2)和(4,5),由于这些“碰巧”是大小为2的元组,它们可以分配给k和v。

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会抱怨试图将它分解为两个变量。

#2


6  

Python has a feature called iterable unpacking. When you do

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

a, b = thing

Python assumes thing is a tuple or list or something with 2 items, and it assigns the first and second items to a and b. This also works in a for loop:

Python假设事物是一个元组或列表或有两个条目的东西,它将第一个和第二个条目分配给a和b。

for a, b in thing:

is equivalent to

相当于

for c in thing:
    a, b = c

except it doesn't create that c variable.

但是它没有创建那个c变量。

This means that if you do

这意味着如果你这么做了

for k, v in d:

Python can't look at the fact that you've said k, v instead of k and 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 k and v variables.

Python不能看到你说k v而不是k给你项而不是键,因为键可能是2元组。它必须遍历键并尝试将每个键解压到k和v变量中。

#3


0  

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

在xx中使用xx时,实际上是使用迭代器来迭代xx,并且xx必须是可迭代的。您可以使用iter函数来获得一个迭代器。

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

and using next to access the elements.

使用next访问元素。

>>> next(i)
'a'

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

所以在k的每一个迭代中,k将被分配到下一个(i),它只是没有值的键。例:在第一轮迭代中,

k = 'a'

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

而.iteritems()将返回另一个带有can的迭代器,使键值组合成一个元组。我们检查这个

>>> 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

看到了吗?在d。iteritems()中的k和v的第一轮,我们实际上得到了这个赋值

k, v = ('a', 1)

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

因此,如果你用k, v在d中,你会得到。

k, v = 'a'

That's an illegal assignment.

这是一个非法作业。

#4


0  

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)检查字典的子属性。

#1


10  

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 k and v.

循环通过键(1,2)和(4,5),由于这些“碰巧”是大小为2的元组,它们可以分配给k和v。

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会抱怨试图将它分解为两个变量。

#2


6  

Python has a feature called iterable unpacking. When you do

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

a, b = thing

Python assumes thing is a tuple or list or something with 2 items, and it assigns the first and second items to a and b. This also works in a for loop:

Python假设事物是一个元组或列表或有两个条目的东西,它将第一个和第二个条目分配给a和b。

for a, b in thing:

is equivalent to

相当于

for c in thing:
    a, b = c

except it doesn't create that c variable.

但是它没有创建那个c变量。

This means that if you do

这意味着如果你这么做了

for k, v in d:

Python can't look at the fact that you've said k, v instead of k and 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 k and v variables.

Python不能看到你说k v而不是k给你项而不是键,因为键可能是2元组。它必须遍历键并尝试将每个键解压到k和v变量中。

#3


0  

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

在xx中使用xx时,实际上是使用迭代器来迭代xx,并且xx必须是可迭代的。您可以使用iter函数来获得一个迭代器。

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

and using next to access the elements.

使用next访问元素。

>>> next(i)
'a'

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

所以在k的每一个迭代中,k将被分配到下一个(i),它只是没有值的键。例:在第一轮迭代中,

k = 'a'

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

而.iteritems()将返回另一个带有can的迭代器,使键值组合成一个元组。我们检查这个

>>> 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

看到了吗?在d。iteritems()中的k和v的第一轮,我们实际上得到了这个赋值

k, v = ('a', 1)

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

因此,如果你用k, v在d中,你会得到。

k, v = 'a'

That's an illegal assignment.

这是一个非法作业。

#4


0  

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)检查字典的子属性。