no classification
no tag
no datas
posted on 2023-05-03 19:31 read(1008) comment(0) like(25) collect(3)
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
How does Python recognize that it needs only to read the key
from the dictionary? Is key
a special keyword, 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 3.x:
for key, value in d.items():
For Python 2.x:
for key, value in d.iteritems():
To test for yourself, change the word key
to poop
.
In Python 3.x, iteritems()
was 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())
.
Author:qs
link:http://www.pythonblackhole.com/blog/article/150/6b40915a26819afe6229/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!