24 of 151 menu

The setdefault method

The setdefault method returns a dictionary element by the specified key. If there is no such key, the specified key and default value will be written to the dictionary, and this value will be returned. In the first parameter of the method, we specify the key we need, in the second optional parameter - the default value.

Syntax

dictionary.setdefault(key, [default value])

Example

Let's find the value for the key 'a' in our dictionary:

dct = { 'a': 1, 'b': 2, 'c': 3 } elm = dct.setdefault('a') print(elm)

Result of code execution:

1

Example

Now let's try to specify in the first parameter of the setdefault method a key that is not in the dictionary:

dct = { 'a': 1, 'b': 2, 'c': 3 } elm = dct.setdefault('e', 4) print(elm) print(dct)

Result of code execution:

4 {'a': 1, 'b': 2, 'c': 3, 'e': 4}

Example

Let's modify the previous example so that there is no default value for a non-existent key:

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

After executing the code, the method will set the key to None:

{'a': 1, 'b': 2, 'c': 3, 'e': None}

See also

  • method keys,
    which returns the keys of the dictionary
  • method values,
    which returns all the values ​​of the dictionary
byenru