Usually I access dict keys using keys() method:
d = {'a':1, 'b':2, 'c':3}
for k in d.keys(): print k
But sometimes I see this code:
for k in d: print k
Is this code correct? safe?
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.
Although this was already mentioned, I wanted to add some exact numbers to these discussion. So I compared:
and
A dictionary with 1 000 000 items was used (float keys) and I used
timeitwith 100 repetitions. These are the results:Obviously calling
dtest.keys()has some downsides in Python 2.x