Python 字典迭代——用于 dict 与用于 dict.items()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24746712/
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 05:07:10  来源:igfitidea点击:

Dictionary Iterating -- for dict vs for dict.items()

pythondictionary

提问by Solaxun

When we iterate over the dictionary below, each iteration returns(correctly) a key,value pair

当我们遍历下面的字典时,每次迭代都会(正确地)返回一个键值对

for key, value in dict.items():
    print "%s key has the value %s" % (key, value)

'some key'key has the value 'some value'(repeated however many times there are a k,v pair)

'some key'键有值'some value'(重复但多次有 ak,v 对)

The above makes sense to me, however if we do this:

以上对我来说很有意义,但是如果我们这样做:

for key in dict.items():
    print "%s key has the value %s" % (key, value)

("some key", "some value")has the value "some value"(the left tuple will iterate through each key value pair and the right value will just stay at the first value in the dict and repeat)

("some key", "some value")有值"some value"(左元组将遍历每个键值对,正确的值将只停留在字典中的第一个值并重复)

We end up getting each k,v pair returned in the first %s(key) and the 2nd %s(value) does not iterate, it just returns the first value in the dict for each iteration of the for loop.

我们最终得到第一个%s(键)中返回的每个 k,v 对,第二个%s(值)不迭代,它只是为 for 循环的每次迭代返回 dict 中的第一个值。

I understand that if you iterate with only for key in dictthen you are iterating over the keys only. Here since we are iterating a set of tuples (by using dict.items()) with only the key in the for loop, the loop should run for the same number of times as the first example, since there are as many keys as key,value pairs.

我明白,如果你只迭代,for key in dict那么你只是在迭代键。在这里,由于我们dict.items()仅使用for 循环中的键来迭代一组元组(通过使用),循环应该运行与第一个示例相同的次数,因为键的数量与键值对一样多。

What I'm having trouble grasping is why python gives you the entire tuple in the second example for key.

我无法理解的是为什么 python 在第二个示例中为您提供了key.



Thanks for the help all -- I'd like to add one more question to the mix.

感谢大家的帮助——我想再添加一个问题。

for a,a in dict.items():
    print a

Why does the above print the value, and if i print a,a- obviously both values are printed twice. If I had typed for a,bI would be iterating (key,value)pairs so I would logically think I am now iterating over (key,key)pairs and would therefore print key rather than value. Sorry for the basic questions just playing around in interpreter and trying to figure stuff out.

为什么上面打印值,如果 i print a,a- 显然这两个值都打印了两次。如果我打字,for a,b我将迭代(key,value)对,所以我会从逻辑上认为我现在正在迭代(key,key)对,因此会打印键而不是值。对于只是在解释器中玩弄并试图弄清楚的基本问题,我深表歉意。

采纳答案by Adam Smith

The first example is utilizing something known as "tuple unpacking" to break what is REALLY the same tuple as in your separate example down into two different variables.

第一个示例是利用称为“元组解包”的东西将与您的单独示例中真正相同的元组分解为两个不同的变量。

In other words this:

换句话说:

for key, value in dict.items():

Is just this:

是不是这样:

for keyvalue in dict.items():
    key, value = keyvalue[0], keyvalue[1]

Remember that a forloop always iterates over the individual elements of the iterator you give it. dict.items()returns a list-like object of tuples, so every run through the forloop is a new tuple, automatically unpacked into key, valueif you define it as such in the forloop.

请记住,for循环总是迭代您给它的迭代器的各个元素。dict.items()返回一个类似列表的元组对象,所以每次for循环运行都是一个新的元组,key, value如果你在for循环中这样定义它,它会自动解包。

It may help to think of it this way:

以这种方式思考它可能会有所帮助:

d = {'a':1, 'b':2, 'c':3}
list(d)          # ['a', 'b', 'c']             the keys
list(d.keys())   # ['a', 'b', 'c']             the keys
list(d.values()) # [1, 2, 3]                   the values
list(d.items())  # [('a',1), ('b',2), ('c',3)] a tuple of (key, value)

N.B. that the only reason your code

请注意,您的代码的唯一原因

for key in dict.items():
    print "%s key has value: %s" % (key, value)

Does not throw a NameErroris because valueis already defined from elsewhere in your code. Since you do not define valueanywhere in that forloop, it would otherwise throw an exception.

不抛出 a NameErroris 因为value已经在您的代码中的其他地方定义了。由于您没有value在该for循环中的任何地方定义,否则它会抛出异常。

回答by ErlVolton

In the second example you gave you are not assigning "value" to anything:

在你给出的第二个例子中,你没有为任何东西分配“价值”:

Notice the small edit here:

注意这里的小编辑:

for key in dict:  ##Removed call to items() because we just want the key, 
                  ##Not the key, value pair
    value = dict[key]  # Added this line
    print "%s key has the value %s (key, value)

Note:

笔记:

In the second example, you could now call dict.keys() or just dict (referencing a dictionary in a for loop will return it's keys). Calling dict.items() will confusingly assign key=(, ) which is probably not what you want.

在第二个示例中,您现在可以调用 dict.keys() 或仅调用 dict (在 for 循环中引用字典将返回它的键)。调用 dict.items() 会混淆地分配 key=(, ) 这可能不是你想要的。