In the last article, we had seen how we can create a dictionary and access an element in it. Today we will dive deep into the main data structure in Python known as Dictionary.
Accessing an element ๐ก
The element in the dictionary can be accessed through the square brackets nomenclature.
dict = {"name": "Nitin", "age": 34, "gender": "male"}
dict["name"]
Result -> Nitin
What if you are trying to access an element that is not in the dictionary?
dict = {"name": "Nitin", "age": 34, "gender": "male"}
dict["address"]
Result -> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'address'
In the above example, the address is not in the dictionary because we are trying to access it from the square brackets.
But we can also leverage the get
method to access the dictionary key
dict = {"name": "Nitin", "age": 34, "gender": "male"}
dict.get("name")
Result -> 'Nitin'
Delete an element with del
method ๐ก
dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict["name"])
print(dict)
Result -> {"age": 34, "gender": "male"}
Delete the dictionary ๐ก
dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict)
print(dict)
Result -> <class 'dict'>
In order to delete the dictionary you have to mention the dictionary variable name in the del
method.
Find the length ๐ก
Finding the length of the dictionary is quite simple.
dict = {"name": "Nitin", "age": 34, "gender": "male"}
len(dict)
Result -> 3
Check if the key exists ๐ก
Not so difficult.
dict = {"name": "Nitin", "age": 34, "gender": "male"}
print("name" in dict)
Result -> True
The boolean would be returned when you try to check the key in the dictionary.
Easy to understand? ๐ก
A dictionary contains
unique keys
a key can have different types of values like
number
,string
,boolean
etc.we can access dictionary elements with multiple approaches
This would look similar to an object in JavaScript
Conclusion ๐
There are more posts on the way related to the tuples...So keep reading.
Thanks in advance for reading this article...๐
I am more than happy to connect with you on
You can also find me on