Python Dictionary items() method
The dictionary.items() method in Python returns a view object that displays a list of dictionary’s (key, value) tuple pairs.
Syntax
1 2 3 |
dictionary.items() |
Parameter
NA
Return
This method returns a view object, displaying the list of the specified dictionary’s tuple pairs.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# the python program representing # the dictionary.items() method # initializing the dictionary fruits = { "banana": "apple", "orange": "mango", "grapes": 5 } # printing the Dictionary print("Dictionary:",fruits) # returns a view object that displays a list of a given dictionary's tuple pair listItem= fruits.items() # printing the list print("The items in the dictionary are:",listItem) |
Output
1 2 3 4 |
Dictionary: {'grapes': 5, 'banana': 'apple', 'orange': 'mango'} The items in the dictionary are: dict_items([('grapes', 5), ('banana', 'apple'), ('orange', 'mango')]) |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 |
# the python program representing # the dictionary.items() method # initializing the week dictionary week = { 'Monday': 1, 'Tuesday': 2, 'wednesday': 3 ,'Thursday':4,'Friday':5} items = week.items() print('Original week list:', items) # deleting an item from the week dictionary del[week['Thursday']] # will return the items after deleting the specified item from the dictionary print('Updated week list:', items) |
Output
1 2 3 4 |
Original week list: dict_items([('Friday', 5), ('wednesday', 3), ('Thursday', 4), ('Tuesday', 2), ('Monday', 1)]) Updated week list: dict_items([('Friday', 5), ('wednesday', 3), ('Tuesday', 2), ('Monday', 1)]) |