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

Definition:

The values() method returns a view object. This view object contains the values of the dictionary in list format. Also, this view object is directly connected to the original dictionary so if any changes occur it will be reflected in the view object as well.

Syntax:

X dictionary.values()

This method takes no argument

Working:

python_dictionary_values

values_dictionary-output

Text format code is here, you can copy.

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

x = dictionary.values()
print(x)
dictionary[‘Subjects’] = ‘Physics’
print(x)

Code:

  1. A dictionary with some random values is being taken
  2. values() method is being applied on it, and a view object inside variable x is created.
  3. Original dictionary is updated
  4. View object is printed after changes made in the original dictionary.

Output:

  1. A view object with only values of the dictionary is printed.
  2. A view object after changes made in the original dictionary.

Interview questions:

  • How will you print only keys of the dictionary in the view object?

To print only keys of the dictionary in the view object we will use the keys() method.

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.