What is keys() method in dictionary | How to use the keys() method of the dictionary.

Definition:

Similar to the items() method, this method also returns a view object, this time the view object contains the keys of the dictionary inside list. Also, this view object is directly connected to the original dictionary, meaning any changes in the original dictionary will be reflected here.

Syntax:

X = dictionary.keys()

This method takes no argument.

Working:

dictionary_method_keys

Keys()_output_method

Code is here you can copy.

dictionary = {1: ‘Student’,
‘Name’: ‘Waqar Khan’,
‘Age’: 23,
‘Male’: True,
‘Subjects’: ‘Computers’}

x = dictionary.keys()
print(x)
dictionary[‘University’] = ‘MU’
print(x)

Code:

  1. A dictionary with some values is being taken
  2. keys() built-in method is being applied to the dictionary.
  3. Since the keys() method returns the values, the output is being printed in x.
  4. After output we have inserted a new key and its value in the original dictionary.
  5. After updating the original dictionary, the value of view object is printed.

Output:

  1. All the keys of the dictionary before updating its content.
  2. All the keys after updating its content.

 

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *