How to get the value of a default value if the key does not exist in `dict()` in Python?

Posted on

How to get the value of a default value if the key does not exist in dict() in Python?

We can use the get() function to assign default value if the key does not exist in the dict yet.

dict.get(key[, default])

Example as follows.

msges = {"msg": "Hello, World!"}

msg = msges.get("msg", "")

print(msg)  # Hello, World!

msg = msges.get("msg2", "hi")

print(msg)  # hi