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)
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)
key's correspondingvalue(s) are expected to also be used somewhere further in the code, whichdict.items()returns a list of its (key, value) tuple pairs. However, if you don't need the values, thendict.keys()function can be (and often is) used. Which function you use may just depend on your needs/requirements.