Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!Using the "[ ]" Operator
A dictionary in Python is not a sequence, as the elements in dictionary are not indexed. Still, you can use the square brackets "[ ]" operator to fetch the value associated with a certain key in the dictionary object.
Example 1
It will produce the following output −
Capital of Gujarat is: Gandhinagar Capital of Karnataka is: Bengaluru
Example 2
Python raises a KeyError if the key given inside the square brackets is not present in the dictionary object.
It will produce the following output −
print ("Captial of Haryana is : ", capitals['Haryana']) ~~~~~~~~^^^^^^^^^^^ KeyError: 'Haryana'
Using the get() Method
The get() method in Python's dict class returns the value mapped to the given key.
Syntax
Parameters
-
key − An immutable object used as key in the dictionary object
Return Value
The get() method returns the object mapped with the given key.
Example 3
It will produce the following output −
Capital of Gujarat is: Gandhinagar Capital of Karnataka is: Bengaluru
Example 4
Unlike the "[]" operator, the get() method doesn't raise error if the key is not found; it return None.
It will produce the following output −
Capital of Haryana is : None
Example 5
The get() method accepts an optional string argument. If it is given, and if the key is not found, this string becomes the return value.
It will produce the following output −
Capital of Haryana is: Not found
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.