get() method in Python Dictionary

In this article, we would cover get() method in Python Dictionary. It returns the value of an associated key. But, things are different with get() method.

Sometimes, we inadvertently or otherwise work with a non-existent key:value pair or item in a dictionary. Since, the item is non-existent therefore, it would throw a KeyError. But, that may not be something which most of us would expect. Therefore, we use get() method to expect None (null value) if the dictionary key isn’t found in a set of keys. Apart from that, we can also use a value of our choice in place of None.

The following is the syntax for get() method –

dictionary_name.get(key_name, value)

Here, default value of parameter value is None. If we want then we can replace None with the value of our choice.

Now, we would understand its functionality with couple of examples next.

get() method in Python Dictionary

Let’s say, we have a dictionary x – which will be common to following examples.

x = {"name": "abc", "address":"XYZ"}

Example I. First, we check for the condition wherein the key we provide isn’t available. Hence, we get KeyError in return. Just use the print() method with a non-existential key – qwerty

print(x["qwerty"])

It would throw an error –

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'qwerty'

Instead of KeyError, we can push the interpreter to provide the value as None through get() method.

print(x.get("qwerty"))

It would return with –

None

Example II. In earlier example, we saw how we could push the interpreter to return None value through get() method. But, what if we could use a different value in place of None?

For that, use the following code –

print(x.get("qwerty", "none_replaced"))

Here, we have provided the optional parameter i.e. value. It replaces None with none_replaced. This is what we get –

none_replaced

In conclusion, we have covered get() method in Python Dictionary here. The method is particularly useful for certain conditions where KeyError is not expected.