Skip to content

Item function in Python | Dictionary method

  • by

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 or suggestions on this Python item() topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *