Why would I use the '.keys()' method?

Hello! This is my first post on these forums, and I do apologize if I’m not posting in the correct category. This is more of a general question regarding the usefulness of the keys() method when dealing with dictionaries.

I’ve noticed so far that for many problems I’ve tried to solve, when I needed to iterate through a dict’s keys, I haven’t ever NEEDED to use the keys() method.

I’ll use the “2. Even Keys” challenge over at cspath-code-challenges-ii as an example for what I’m trying to illustrate:

The challenge asked me to return the total sum of the values of even keys in a given dictionary. For that, I needed to iterate through the dictionary’s keys and check if they were even.

I could easily just write:

for key in my_dictionary:

instead of:

for key in my_dictionary.keys():

to achieve my desired result.

Another example would be when I need to create a list of a dictionary’s keys. All I need to do is ‘list(my_dictionary)’ instead of ‘list(my_dictionary.keys())’.

Could someone give me an example of a situation where the ‘.keys()’ method is truly necessary?

The difference between dict.keys() and list(dict) is that the former returns a view object of the dictionary which gets updates when the original dictionary get updated.

var = {"test1" : 2, "test2": 4}

var_list = list(var)
var_vieuw = var.keys()

var["test3"] = 3

print(f"List: {var_list}")
print(f"dict.keys {var_vieuw}")

The code above prints the content of both var_list and var_view, but only the var_view is reflecting the current state of the dictionary:

List: ['test1', 'test2']
dict.keys dict_keys(['test1', 'test2', 'test3'])

This of course eliminates the need to create a new variable whenever the dictionary changes.

1 Like

I see, now. Thank you for that information.