Python

Get Value from Dictionary Python

A dictionary is one of Python’s most fundamental data types. A Python dictionary is a collection of data values expressed in the form of key-value pairs.

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:

i = {

    "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:

print(i["key1"])

This should automatically return the value stored in the key “key1”. The result is as shown below:

"value1"

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:

dict_name.get(key, value).

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:

langauges = {

    "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.

print(langauges.get(key="Ruby", value="Key not Found!"))

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list