For the explicit principle, for k in dict.keys():
seems better.
For simplicity, for k in dict:
seems better.
Please help me to make a decision.
For the explicit principle, for k in dict.keys():
seems better.
For simplicity, for k in dict:
seems better.
Please help me to make a decision.
For functionality, are they exactly the same?
Pretty much yes. dict.keys()
actually returns a dict view which is a set, so you can do a few more things with it, but for iteration they'll do the same thing.
For the explicit principle, for k in dict.keys(): seems better.
For simplicity, for k in dict: seems better.
In my experience, both are rarely useful, it's much more common to want and use dict.items()
(which really is what the default iterator should have been).
As a result I would recommend dict.keys()
to express that you really actually want to iterate on or manipulate dict keys, and are not just misunderstanding what dict iteration does.