Is there any advantage to using keys() function?
for word in dictionary.keys():
print word
vs
for word in dictionary:
print word
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.
Yes, in Python 2.x iterating directly over the dictionary saves some memory, as the keys list isn’t duplicated.
You could also use
.iterkeys(), or in Python 2.7, use.viewkeys().In Python 3.x,
.keys()is a view, and there is no difference.So, in conclusion: use
d.keys()(orlist(d.keys())in python 3) only if you need a copy of the keys, such as when you’ll change the dict in the loop. Otherwise iterate over the dict directly.