⊗pyPmDcEBK 95 of 208 menu

Extracting an Element by Key in Python

You can extract an element from a dictionary. In this case, the element will be removed from the dictionary and we will receive it in a variable. For such an operation, you need to use the pop method. Its parameter specifies the key of the element to be extracted.

Let's look at an example. Let's say we have the following dictionary:

dct = { 'a': 1, 'b': 2, 'c': 3 }

Let's extract the element with key 'a':

print(dct.pop('a')) # 1

This element will disappear from the dictionary:

print(dct) # {'b': 2, 'c': 3}

If the key is not in the dictionary, an error will be returned:

print(dct.pop('x')) # will display an error

You can set the second parameter of the method pop. In this case, if the key is not in the dictionary, the value specified by the parameter will be returned. Let's check:

print(dct.pop('x', '!')) # '!'

Given a dictionary:

dct = { 'x': 1, 'y': 2, 'z': 3 }

Get the element with key 'x' from it, removing it from the dictionary.

The following code is given:

dct = { 1: '1', 2: '2', 3: '3' } print(dct.pop('2'))

Tell me what will be output to the console.

The following code is given:

dct = { 'surn': 'smith', 'name': 'john', 'age': 30 } dct.pop('surn') print(dct)

Tell me what will be output to the console.

byenru