This tutorial will discuss using the get() function to get a value in a Python dictionary.
How to Define a Python Dictionary
Let us start at the very basics: learning how to define a dictionary in Python. Since python dictionaries are expressed in key-value pairs, each key in a dictionary must be unique.
To define a dictionary, we add comma-separated values inside a pair of curly braces. The comma-separated values represent key:value.
The following is an example of a simple dictionary:
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Each key in a dictionary gets automatically mapped to its corresponding value.
How to Access Dictionary Values
To access a specific value in a dictionary, you can use the dictionary name, followed by the specific key in square brackets.
An example:
This should automatically return the value stored in the key “key1”. The result is as shown below:
How to Get Values from Dictionaries Using the Python Get Method
Python also provides us with a method to retrieve values mapped to a specific key in a dictionary: the get method. The Python get() method accepts the key as an argument and returns the value associated with the key.
If the specified key is not found, the method returns a None type. You can also specify the default return value if the key is not found.
The syntax for the method is:
NOTE: The value, in this case, is not the value in the dictionary key but the return value if the key is not found.
Example:
Suppose we have a dictionary of programming languages mapped to their authors as:
"Java": "James Gosling",
"C": "Dennis Ritchie",
"C++": "Bjarne Stroustrup",
"Python": "Guido Van Rossum",
"Ruby": "Yukihoro Matsumoto"
}
In this case, we can use the get method to get the creator of a specific language. For example, the code below shows the author of Ruby.
If we specify a non-existent key, we should get “Key not Found!” Error.
Conclusion
As this tutorial has shown you, you can use the default indexing method to retrieve a value from a Python dictionary or the get() method. Choose what works for you and stick with it.