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. How does Python recognize that it needs only to read the key from the dictionary? Is key
a special word in Python? Or is it simply a variable?
key
is just a variable name.
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:
for key, value in d.iteritems():
For Python 3.x:
for key, value in d.items():
To test for yourself, change the word key
to 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. This is also available in 2.7 as 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. If you want the 2.x behavior in 3.x, you can call list(d.items())
.
It's not that key is a special word, but that dictionaries implement the iterator protocol. You could do this in your class, eg see this question for how to build class iterators.
In the case of dictionaries, it's implemented at the C level. The details are available in PEP 234. In particular, the section titled "Dictionary Iterators":
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ...
for value in dict.itervalues(): ...
for key, value in dict.iteritems(): ...
This means that for x in dict
is shorthand for for x in dict.iterkeys()
.
Iterating over a dict
iterates through its keys in no particular order, as you can see here:
Edit: (This is no longer the case in Python3.6 , but note that it's not guaranteed behaviour yet)
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> list(d)
['y', 'x', 'z']
>>> d.keys()
['y', 'x', 'z']
For your example, it is a better idea to use dict.items()
:
>>> d.items()
[('y', 2), ('x', 1), ('z', 3)]
This gives you a list of tuples. When you loop over them like this, each tuple is unpacked into k
and v
automatically:
for k,v in d.items():
print(k, 'corresponds to', v)
Using k
and v
as variable names when looping over a dict
is quite common if the body of the loop is only a few lines. For more complicated loops it may be a good idea to use more descriptive names:
for letter, number in d.items():
print(letter, 'corresponds to', number)
It's a good idea to get into the habit of using format strings:
for letter, number in d.items():
print('{0} corresponds to {1}'.format(letter, number))
链接地址: http://www.djcxy.com/p/796.html
上一篇: 什么是在C#中迭代字典的最佳方式?
下一篇: 使用'for'循环遍历字典