Is there any advantage to using keys() function?
for word in dictionary.keys():
print word
vs
for word in dictionary:
print word
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With