Python dictionary Method - keys()

htt‮www//:sp‬.theitroad.com

The keys() method is a built-in dictionary method in Python that returns a view object that contains the keys of the dictionary. The order of the keys is not guaranteed. You can use this method to loop over the keys of a dictionary.

Here's the syntax for the keys() method:

keys = my_dict.keys()

Here, my_dict is the dictionary to get the keys from, and keys is the view object that contains the keys.

Here's an example:

# create a dictionary
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}

# get the keys
keys = my_dict.keys()

# print the keys
for key in keys:
    print(key)

Output:

apple
banana
cherry

In this example, we create a dictionary my_dict with three key-value pairs. We then use the keys() method to get a view object that contains the keys. We loop over the keys using a for loop and print each key.

The keys() method is useful when you need to loop over the keys of a dictionary. You can also use the keys() method to check if a key is in a dictionary. For example:

# create a dictionary
my_dict = {'apple': 3, 'banana': 2, 'cherry': 5}

# check if 'apple' is a key in the dictionary
if 'apple' in my_dict.keys():
    print('Yes')
else:
    print('No')

Output:

Yes

In this example, we use the keys() method to check if the key 'apple' is in the my_dict dictionary. Since 'apple' is a key in the dictionary, the output is 'Yes'.