Python Dictionary items()

Python dictionary items() method

Python dictionary items() method returns a set-like object that can provide a view on the dictionary’s items. Each item in the dictionary is a key-value pair.

In this tutorial, you will learn about dictionary items() method in Python, and its usage, with the help of example programs.

Syntax of dict items()

The syntax of dictionary items() method is

dictionary.items()

Parameters

The dictionary items() method takes no parameters.

Return value

The dictionary items() method returns an object of type dict_items.

Examples for items() method

1. Getting the items of given dictionary in Python

In this example, we are given a dictionary in my_dict with some initial key:value pairs. We have to get the items (key-valule pairs) in this dictionary.

We shall call items() method on the given dictionary object my_dict, and print the returned value to standard output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

print(my_dict.items())
Run Code Copy

Output

dict_items([('foo', 12), ('bar', 14)])

Each item is a tuple of key and value.

You may convert the dict_items object to a list using list() built-in function.

In the following program, we shall convert the dict_items object to a list, store this list in items, and then printed this list of items to output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

items = list(my_dict.items())
print(items)
Run Code Copy

Output

[('foo', 12), ('bar', 14)]

2. Iterate over items of dictionary using items() method in Python

In this example, we will use dictionary items() method to iterate over the items of the dictionary in a For loop. During each iteration, we shall access the key and value from the item, and print them to output.

Python Program

my_dict = {
    'foo':12,
    'bar':14
}

for item in my_dict.items():
    print(f"key : {item[0]}, value : {item[1]}")
Run Code Copy

Output

key : foo, value : 12
key : bar, value : 14

Summary

In this tutorial of Python Dictionary Methods, we learned how to use Dictionary items() method to get the items in a dictionary, with help of well detailed Python programs.

Related Tutorials

Code copied to clipboard successfully 👍