Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using keys() function when iterating over a dictionary

Tags:

python

Is there any advantage to using keys() function?

for word in dictionary.keys():
    print word

vs

for word in dictionary:
    print word
like image 276
Sajad Rastegar Avatar asked Dec 19 '12 20:12

Sajad Rastegar


1 Answers

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() (or list(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.

like image 181
Martijn Pieters Avatar answered Sep 30 '22 12:09

Martijn Pieters