2

I've seen a few people saying

for key, value in dict.items():
    print(key)

is a more pythonic way than others. Why isn't people using keys() function?

for key in dict.keys():
    print(key)
2
  • sometimes the key's corresponding value(s) are expected to also be used somewhere further in the code, which dict.items() returns a list of its (key, value) tuple pairs. However, if you don't need the values, then dict.keys() function can be (and often is) used. Which function you use may just depend on your needs/requirements. Commented Mar 4, 2019 at 19:58
  • 1
    Must have clicked twice :( Commented Mar 4, 2019 at 22:53

1 Answer 1

2

Because if you only need the keys, then a dict object as an iterable would generate the keys already:

for key in dictionary:
    print(key)

And if you need the values of the dict, then using the items method:

for key, value in dictionary.items():
    print(key, value)

makes the code more readable than using a key to access the dict value:

for key in dictionary:
    print(key, dict[key])

The only practical use for the keys method is to make set-based operations, since the keys method returns a set-like view:

# use set intersection to obtain common keys between dict1 and dict2
for key in dict1.keys() & dict2.keys():
    print(key)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.