Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

python - 使用“ for”循环遍历字典(Iterating over dictionaries using 'for' loops)

I am a bit puzzled by the following code:

(以下代码使我有些困惑:)

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    print key, 'corresponds to', d[key]

What I don't understand is the key portion.

(我不明白的是key部分。)

How does Python recognize that it needs only to read the key from the dictionary?

(Python如何识别只需要从字典中读取密钥?)

Is key a special word in Python?

(key在Python中是一个特殊的词吗?)

Or is it simply a variable?

(还是仅仅是一个变量?)

  ask by TopChef translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

key is just a variable name.

(key只是一个变量名。)

for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values.

(只会循环遍历字典中的键,而不是键和值。)

To loop over both key and value you can use the following:

(要遍历键和值,可以使用以下命令:)

For Python 2.x:

(对于Python 2.x:)

for key, value in d.iteritems():

For Python 3.x:

(对于Python 3.x:)

for key, value in d.items():

To test for yourself, change the word key to poop .

(要进行自我测试,请将单词key更改为poop 。)

For Python 3.x, iteritems() has been replaced with simply items() , which returns a set-like view backed by the dict, like iteritems() but even better.

(对于Python 3.x, iteritems()已替换为简单的items() ,它返回了由dict支持的类似set的视图,就像iteritems()但效果更好。)

This is also available in 2.7 as viewitems() .

(在2.7中也可以通过viewitems() 。)

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call.

(操作items()将同时适用于2和3,但是在2中它将返回字典的(key, value)对的列表,该列表将不反映对items()调用后字典的更改。)

If you want the 2.x behavior in 3.x, you can call list(d.items()) .

(如果要在3.x中使用2.x行为,可以调用list(d.items()) 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...