Difference between using .keys() and just the name of the dictionary,

If I have the following dictionary:

items = {“H”: 10, “C”: 5, “G”: 20, “W”: 25, “S”: 15, “P”: 30}

and print:

for item in items.keys():
print(item)

or:

for item in items:
print(item)

I get the same output. Why? It’s there a reason why I should use one or the other?
Thank you for your help.

Hello @objectace30675, welcome to the forums! In the way you are using them now, no, there is not much difference (there might be something to do with timing, but I’m not sure). However, the .keys() is useful. It returns a list of the keys in a dictionary. Take the following example:

a = {"a": "1", "b": "2", "c": "3"}
print(a.keys())

This will print:

>>dict_keys(["a", "b", "c"]}

This would be useful if one wanted to get the keys of a dictionary. That way, it is easier to separate the keys of a dictionary from the values of a dictionary.
I hope this helps!

1 Like

Thanks for your answer. Sometimes I like to tinker with different answers for the exercises and questions arise.

1 Like