⊗pyPmDcOEG 99 of 208 menu

Optionally get an element from a dictionary in Python

EAnother way to get an element is to use the get method. In the first parameter of the method, we specify the key by which the search will be performed. If the key exists, the corresponding element will be returned, otherwise - None.

Let's look at it in practice. Let's say we have the following dictionary:

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

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

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

Now let's try to get the element with key 'x':

print(dct.get('x')) # None

In the second parameter of the get method, you can set a default value for the missing element. This may be needed when the output None is not desired for some reason. Let's specify the value 4 for the key 'x':

print(dct.get('x', 4)) # 4

The following code is given:

dct = { 1: 'x', 2: 'y', 3: 'z', 4: 'w' } print(dct.get(4))

Tell me what will be output to the console.

The following code is given:

dct = { 1: 'a', 2: 'b', 3: 'c', 4: 'd' } print(dct.get('3'))

Tell me what will be output to the console.

Given a dictionary:

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

Get from it the element with key 'w' such that its default value is '!'.

byenru