Item function in Python | Dictionary method

A items() method is used with a dictionary to get the list with all dictionary keys with values. This method actually returns a view object that contains the key-value pairs of the dictionary, as tuples in a list.

Item function syntax:-

dictionary.items() 

Example Item function in Python

Simple example code. Get all items of a dictionary with items() function.

a_dict = {"A": 10, "B": 20, "C": 30}

x = a_dict.items()

print(x)

Output:

Item function in Python

Delete an item from the dictionary

Using a del keyword with item function by key.

a_dict = {"A": 10, "B": 20, "C": 30}

x = a_dict.items()

del[a_dict["A"]]
print(x)

Output: dict_items([(‘B’, 20), (‘C’, 30)])

Modify an item value of the dictionary

If an item in the dictionary changes value (update), the view object also gets updated.

a_dict = {"A": 10, "B": 20, "C": 30}

x = a_dict.items()

a_dict["A"] = 500
print(x)

Output: dict_items([(‘A’, 500), (‘B’, 20), (‘C’, 30)])

Do comment if you have any doubts a suggestions on this Python item() topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.