Python popitem

Python popitem

In Python, the popitem method, on dictionaries, removes the last key: value pair entered in the dictionary. Furthermore, this method adds the deleted pair as a tuple.

This method has no parameters, so its syntax is simply this:

d.popitem()

If the dictionary has no elements the method returns a keyError.

Python popitem – first example

In this first example we delete the last element from our student dictionary.

Here is a possible implementation of the proposed algorithm:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
student.popitem()
print(student)

In output we will see this result:

{'name': 'Cristina', 'age': 20}

Try the above code in the online compiler which you will find at the following link: online Python compiler.

Now we also print the deleted element always using the Python popitem method on the dictionaries:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
del_student = student.popitem()
print(del_student)
print(student)

In this case, the output generated is the following:

('mail', 'info@codingcreativo.it')
{'name': 'Cristina', 'age': 20}

Python popitem – second example

This time we will try to delete from an empty dictionary.


student = {}
del_student = student.popitem()
print(del_student)
print(student)

An error message will be returned, noting that the dictionary is empty:

Traceback (most recent call last): File “/tmp/sessions/95c2c3a3544875f9/main.py”, line 2, in <module> del_student = student.popitem() KeyError: ‘popitem(): dictionary is empty’

It is very important to know how to read errors, so experiment every time you are faced with a new topic.

Conclusion

In this lesson we talked about the popitem method on dictionaries in Python, later we will see how to put these methods into practice.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Python dictionary pop

Python dictionary pop

In Python, the pop method on the dictionary, allows you to remove an element from the dictionary in question.

The method accepts two parameters, one mandatory, the other optional. The syntax is, therefore, the following:

d.pop(keydef)

Where key removes all the key: value pair from the dictionary d. This parameter is mandatory. This means that I cannot write d.pop(), it would result in an error (keyError).

While def represents the default value to return if the key does not exist, this way you can avoid the (keyError). This parameter, on the other hand, is optional.

Python dictionary pop – first example

In this first example, taking the student dictionary into consideration, let’s try to delete a key: value pair.

So here’s a code example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
student.pop('age')
print(student)

Try it in the online Python compiler that you will find at the following link: online compiler.

The displayed output will be the following:

{‘name’: ‘Cristina’, ‘mail’: ‘info@codingcreativo.it’}
We also try to print the deleted item.


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
del_element = student.pop('age')
print(del_element)
print(student)

Thus we are able to print the deleted element, as well as the dictionary with the missing element.

Python dictionary pop – second example

In this second example, we take the same dictionary as the previous example as a reference but, this time, we try to delete a key that does not exist.

Here, then, is a possible example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
student.pop('surname')
print(student)

In this case there is an error like:

Traceback (most recent call last): File “/tmp/sessions/7ad116a7a00a02b7/main.py”, line 4, in student.pop (‘surname’) KeyError: ‘surname’

This is a KeyError, this clearly indicates that there is an error in the surname key.

If instead we specify the optional def parameter, the error will not be returned, but what is specified in def.

So here’s an example:


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
del_element = student.pop('surname','non presente')
print(del_element)
print(student)

The output displayed is this:

non presente
{'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'}

Conclusion

In this lesson, on Python, we studied the pop method on the dictionary, creating two simple practical examples in order to understand how it works.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Python items

Python items

The Python items method on dictionary is used to return the list with all the dictionary keys with values.

This method takes no parameters, so the syntax is very simple: d.items(), where d represents the dictionary.

The items() method, therefore, returns an object that displays a list of pairs of tuples (key, value) of a dictionary.

Python items – first example

In this first simple example we print the pairs of tuples (key, value) on the student dictionary, which contains the data of a student.


student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}

print(student.items())

The output will be represented by this object which contains the pairs of tuples:

dict_items([('name', 'Cristina'), ('age', 20), ('mail', 'info@codingcreativo.it')])

The order could also be different.

Python items – second example

Let’s try now with a dictionary whose values ​​are in turn dictionaries. The students dictionary which contains the data of 2 students.

We want to use Python’s items () method on the entire dictionary. What will the result be?


students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}
}

print(students.items())

The output generated will be this:

dict_items([('1', {'name': 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'}), ('2', {'name': 'Tom', 'age': 23, 'mail': 'info@prova.it'})])

Try the following code in the online compiler that you find at the following link: online Python compiler.

Python items – third example

Now we want to use the items method on internal dictionaries. How can we do?

In order to use the items method, for this purpose, we must first select the key whose pairs of tuples we want to obtain. Then we can apply the method.

Here is therefore a possible solution to the proposed algorithm:


students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}
}

student = students.get('1', {}).items()
print(student)

In this case, the output generated will be this:

dict_items([('name', 'Cristina'), ('age', 29), ('mail', 'info@codingcreativo.it')])

This is if the dictionaries are the same, but what if the values ​​of keys 1 and 2 are represented by different dictionaries?


''' 
Example with different keys
'''
students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'exam' : 'English', 'vote': 30}
}

for student in students.values():
  print(student.items())

In this case, the output will be the following:

dict_items([('name', 'Cristina'), ('age', 29), ('mail', 'info@codingcreativo.it')])
dict_items([('exam', 'English'), ('vote', 30)])

Conclusion

In this lesson we have made some simple examples of using the items () method in Python on dictionaries. In the next lesson we will see what happens if we delete or add elements to a dictionary.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot