Last Updated on May 28, 2024 by Roshan Parihar
To get dictionary value by key in Python, use the get()
function and pass the key to find its value.
You can also get value by key using the index operator. Let’s find out with the examples given below.
Get Dictionary Value By Key Using Get() Function in Python
You can use the get()
function and pass the key of the Dictionary for which you want to get its value in Python.
Example 1
1 2 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill', 'five': 33, 'six': 'Steve'}; print(myDict.get("one")); |
Output
The above example contains 6 elements with both keys and the associated value of the dictionary. It finds the value of the key “one” of Dictionary in Python. This gives value in the 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
The index operator ([]) is also useful in Python to find the value of the given key of the Dictionary. It requires a single argument as the key to passing to find its value from Dictionary in Python.
Example 2
1 2 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill', 'five': 33, 'six': 'Steve'}; print(myDict["one"]); |
Output
The above example shows 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 a 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.
Example 3
1 2 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill', 'five': 33, 'six': 'Steve'}; print(myDict.get("seven", "Champ")); |
Output
The above example shows the output as the default value for the given key. The key given in the get() function argument does not match the key in Dictionary. You can use this method if you have no idea about the key in the Dictionary to avoid the error message.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read