字典迭代-dict与dict.items() [英] Dictionary Iterating -- for dict vs for dict.items()

查看:63
本文介绍了字典迭代-dict与dict.items()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'键的值是'some value'(重复多次,但有k,v对)

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

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

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")具有值"some 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)

我们最终在第一个%s (键)中返回每个k,v对,而第二个%s (值)不进行迭代,它只返回for 循环每次迭代的 dict 中的第一个值.

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.

我了解,如果仅使用 for dict中的键进行迭代,那么您仅在键上进行迭代.在这里,由于我们仅使用for循环中的键来迭代一组元组(通过使用 dict.items()),因此该循环应运行与第一个示例相同的次数,因为键与键,值对一样多.

I understand that if you iterate with only for key in dict then 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.

我难以理解的是,为什么在第二个示例中,python为您提供了整个元组 key .

What I'm having trouble grasping is why python gives you the entire tuple in the second example for 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

以上为什么打印此值,如果我打印a,a -显然两个值都打印两次.如果我为a,b 输入,我将迭代(key,value)对,因此从逻辑上讲,我现在认为我正在遍历(key,key)对,因此将显示键而不是值.抱歉,只是在解释器中玩耍并试图弄清楚东西的基本问题.

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,b I 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.

推荐答案

第一个示例是利用所谓的元组拆包"将与您单独的示例中的真正相同的元组分解为两个不同的变量.

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.

换句话说:

for key, value in dict.items():

就是这样:

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

请记住, for 循环始终会迭代您赋予它的迭代器的各个元素. dict.items()返回一个类似元组的列表对象,因此每次通过 for 循环运行的都是一个新的元组,该元组会自动解包为 key,value (如果您在 for 循环中如此定义).

Remember that a for loop 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 for loop is a new tuple, automatically unpacked into key, value if you define it as such in the for loop.

这样思考可能会有所帮助:

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)

不引发 NameError 是因为您的代码中的其他地方已经定义了 value .由于您没有在 for 循环中的任何地方定义 value ,否则它将引发异常.

Does not throw a NameError is because value is already defined from elsewhere in your code. Since you do not define value anywhere in that for loop, it would otherwise throw an exception.

这篇关于字典迭代-dict与dict.items()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆