What Is Values() Method In Dictionary In Python-Kaizensk

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:

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.



Source link