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

Definition:

This method returns a view object, a view object contains a list of tuples.

 [ ( ) , ( ) , ( ) , ( ) ] and these tuples contain key value pairs. Also this view object is directly connected to the original dictionary, meaning any changes in the original dictionary will be reflected directly into view object.

Syntax:

X = dictionary.items()

This method takes no argument.

Working:

item_output_python_dictionary

You can copy code here.

dictionary = {1: ‘Student’,
‘Name’: ‘Waqar Khan’,
‘Age’: 23,
‘Male’: True,
‘Subject’: ‘Computers’}
x = dictionary.items()
print(x)
dictionary[‘Subject’] = ‘Physics’
print(x)

Code:

  1. A dictionary with some values is being taken
  2. items() method is being applied to the dictionary and that result is passed in the ‘x’ variable which becomes a view object for the dictionary.
  3. Now, dictionary is updated with its subject’s value to Computers.
  4. No changes are explicitly made inside ‘x’ which is a view object, but since it is a view object, it will reflect changes.

Output:

  1. A list of tuples with key value pairs is printed.
  2. An updated view object is printed.

Related Post.



Source link