How To Get Dictionary Value By Key Using Python

In this tutorial, learn how to get dictionary value by key in Python. If you want to find the value of a known key, you have to use the Python get() function.

The dictionary contains the keys with its associated values. The values in the dictionary variable can be identified by the key. However, if you want to know more about the dictionary, you may like to read Python Dictionary.

Get Dictionary Value By Key With Get() in Python

To get the value of the key you want, you have to use the get() function using Python. The function requires a single argument which is the key in the dictionary.

How To Get Dictionary Value By Key Using Python

The below example contains 6 elements with both keys and the associated value of the dictionary. Use the method given below to get the value using the get() with Python.

Output

Ram

The above example finds the value of the key “one” of Dictionary in Python. This gives value in Dictionary for the single key given. However, to get more values with the keys, you have to use the get function again.

Find the Value Using Index Operator in Python

In addition to the above method, you can also get the values by keys in Dictionary. You have to use the Python index operator([]) to find the value of the given key.

The index operator requires a single argument to pass. You have to just pass the known key as the argument of the index operator. See the below method to get the use of index operator to get values.

Output

Ram

The above example showing the output as the value for the given key. The index value for the output is ‘one’ which is the argument of the index operator.

Set Default Value For the Unknown Key Using Python

Suppose you have a key which is not present in the dictionary in Python. The output gives an error message when you execute the code with the single argument in get().

However, if you use the second argument for the get(), the argument works as the default value for the given key. If the key is not present in the dictionary, the code prints the default value upon execution.

Output

Champ

The above example showing the output as the default value for the given key. The key given in the get() function argument is not matching with the key in Dictionary. You can use this method if you have no idea about the key in Dictionary to avoid the error message.

You may also like to read

Hope, you like this post of how to find the value for the given key in Dictionary. If you have any query regarding the tutorial, please comment below.

References

Also tell me, which method you are using to find the value of your key in the dictionary.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.