Menu Close

Python Dictionary items Method

In this dictionary method article, we are going to learn all about the Python dictionary items() method to return the list with all the dictionary keys with values.
In the previous tutorial, we have learned the python dictionary get method to get the value of the specified key.

To understand this example, you should have a basic knowledge of Python Dictionary.

Python Dictionary items Method

Python dictionary items method is a pre-defined dictionary method, that is used to return the list with dictionary keys and their values.

Syntax

The syntax of python dictionary items method is:-

dictionary.items()

Parameter

Dictionary items function in Python does not accept parameter.

Return Value

items function in Python return list which contains tuple of key-value pair.

Python Dictionary items Example

Here we will use the dictionary items function to return a view object. The view object contains the key-value pair of the dictionary, as a tuple.

Example 1:

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.items()
print(result)

Output

dict_items([('first_name', 'Vishvajit'), ('last_name', 'Rao'), ('roll_no', 120), ('course', 'BCA')])

Loop through the return list:

You can use for loop to iterate the list returned by the dictionary items fucntion.

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.items()

for i in result:
	print(i)

Output

('first_name', 'Vishvajit')
('last_name', 'Rao')
('roll_no', 120)
('course', 'BCA')

Note:- Any changes made in the original dictionary will reflect the returned list.

Example 3:

Details = {'first_name': 'Vishvajit', 'last_name': 'Rao', 'roll_no': 120, 'course': 'BCA'}
result = Details.items()
Details['course'] = 'BTech'

for i in result:
	print(i)

Output

('first_name', 'Vishvajit')
('last_name', 'Rao')
('roll_no', 120)
('course', 'BTech')

Conclusion

In this guide, you have seen all about the dictionary items method to get the list that contains the tuple of the key-value pair.
If this article helped you, please continue visiting for further interesting python tutorial.

Other Dictionary Methods


For Reference:- Click Here

Python Dictionary clear Method
Python Dictionary keys Method

Related Posts