Python Dictionary items() Method

The items() method in Python is a built-in method that returns a list of the dictionary’s (key, value) tuple pairs. This method is commonly used when working with dictionaries in Python to iterate over the keys and values or to create a new dictionary.

Syntax

dict.items()

Parameters

The items() method does not take any parameters. It simply returns a list of the dictionary’s (key, value) tuple pairs.

Examples

Example 1: Iterating Over the Dictionary’s (key, value) Tuples

Consider the following example, where we iterate over the items of a dictionary:

student = {'name': 'John', 'age': 25, 'gender': 'Male'}
for key, value in student.items():
    print(key, value)

In this example, we have created a dictionary called student, which contains the key-value pairs of a student. Then, we use a for loop to iterate over the items of the dictionary using the items() method. In each iteration, the (key, value) tuple is unpacked and assigned to the variables key and value, respectively. Finally, we print the key and value of each iteration.

Example 2: Converting a Dictionary to a List of Tuples

Consider the following example, where we convert a dictionary to a list of tuples:

student = {'name': 'John', 'age': 25, 'gender': 'Male'}
student_list = list(student.items())
print(student_list)

In this example, we have created a dictionary called student, which contains the key-value pairs of a student. Then, we use the list() function to convert the items of the dictionary to a list of tuples using the items() method. Finally, we print the resulting list, which will be:

[('name', 'John'), ('age', 25), ('gender', 'Male')]

Example 3: Creating a New Dictionary from a List of Tuples

Consider the following example, where we create a new dictionary from a list of tuples:

student_list = [('name', 'John'), ('age', 25), ('gender', 'Male')]
student = dict(student_list)
print(student)

In this example, we have created a list of tuples called student_list, which represents the key-value pairs of a student. Then, we use the dict() function to create a new dictionary from the list of tuples. Finally, we print the resulting dictionary, which will be:

{'name': 'John', 'age': 25, 'gender': 'Male'}

In conclusion, the items() method is a useful method when working with dictionaries in Python. It allows us to iterate over the dictionary’s (key, value) tuple pairs, convert the dictionary to a list of tuples, or create a new dictionary from a list of tuples. It is a versatile method that should be in every Python developer’s toolkit.

Leave a Reply

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