Seung
Seung

Reputation: 833

python dictionary get keys

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)

Upvotes: 2

Views: 2053

Answers (1)

blhsing
blhsing

Reputation: 107134

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)

Upvotes: 2

Related Questions