Sajad Rastegar
Sajad Rastegar

Reputation: 3154

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

Is there any advantage to using keys() function?

for word in dictionary.keys():
    print word

vs

for word in dictionary:
    print word

Upvotes: 6

Views: 455

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

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.

Upvotes: 12

Related Questions