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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
keyis just a variable name.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 Python 2.x:
To test for yourself, change the word
keytopoop.In Python 3.x,
iteritems()was replaced with simplyitems(), which returns a set-like view backed by the dict, likeiteritems()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 theitems()call. If you want the 2.x behavior in 3.x, you can calllist(d.items()).