The dictionary is a key/value collection used in Python. The name comes from the real-world dictionary like a word and its meaning where a key and its value. The value of a specific item or key can get in different ways. The get()
method is used to get a value from the dictionary with its key.
Get Value
The dictionary type provides the get() method in order to return the value of the specified key. The get() method syntax is like below.
dict.get(KEY)
- KEY is the key to which value will be returned.
In the following example, the dictionary has the “name”->”ismail” and “age”->35 key->value pairs. We will use the get() method by providing the “name” key in order to get its value.
person = {"name":"ismail","age":35}
print(person.get("name"))
Alternatively, the list syntax can be used to get the value of the specified key. The key will be specified as an index.
person = {"name":"ismail","age":35}
print(person["name"])
But if we provide a non-existing key for this syntax we will get an error because the key does not exist and there is no value to return.
person = {"name":"ismail","age":35}
print(person["country"])
Get Non-Existing Value
So using the get() method is the best way to in order to prevent errors and exceptions while returning specified keys value. A second parameter named default can be provided which will be returned if the specified do not exist. The default
parameter can be used to return a value that does not exist where a default value is returned instead of the exception. In the following example, we try to get country from the dictionary but as it does not contains it we set the “turkey” as a default value to return.
person = {"name":"ismail","age":35}
print(person.get("country",default="turkey"))
Get All Values
The dictionary data type provides the values() method which will return all values. But keep in mind that will do not provide the key and value relation so there is no way to find which keys value is what.
person = {"name":"ismail","age":35}
persone.values()