How To Get Dictionary Value By Key Using Python

In this tutorial, learn how to get dictionary value by key in Python. The short answer is to use the Python get() function to find the value of a known key.

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.

Bonus: download a Free Python cheat sheet that will show you 20+ most important examples to learn in Python.

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.

DOWNLOAD Free PYTHON CHEAT SHEET

You may also like to read

I hope you like this post on how to find the value for the given key in Dictionary.

References