-3

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.

zhigang
  • 6,597
  • 4
  • 30
  • 24
  • 1
    https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops – tomgalpin Jan 30 '20 at 15:13
  • Thank you for the link @tomgalpin. I mainly want to know from style's point of view, which one is more beautiful. I adjusted my question to make it more clear. – zhigang Jan 30 '20 at 15:37

1 Answers1

2

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.

Community
  • 1
  • 1
Masklinn
  • 34,759
  • 3
  • 38
  • 57