Dictionary
I LOVE DOING THIS :)
Dictionary is a set of unordered key, value pairs, the keys must be unique and they are stored in an unordered manner so hence they are Immutable
Creating a Dictionary
Separate the key-value pairs by a colon
:
The keys would need to be of an immutable type
Individual pairs will be separated by a comma
,
and the whole thing will be enclosed in curly braces{...}
So here the name
is the key and Akash
is the value pair, inorder to retrieve a single value from a dictionary we can simply use the method called Direct Referencing
Always remember to use square brackets
[]
to call the value pair within the Dictionary
We can also use the get
method to retrieve the values in a dictionary. The only difference is that in the get method, you can set a default value. In Direct Referencing, if the key is not present, the interpreter throws KeyError
Looping over Dictionary
Pre-requisites are the basics of looping statements and keywords such as for
and in
Here arises a question, why can't we use the keyword enumerate(osint)
instead of osint.items()
and here is the reason
The enumerate
keyword considers the key values as integers (starting from 0) by default and takes the key as the value pair, we used the enumerate
keyword when it came to lists because there was no such thing called keys
, Since we wanted an index to be assigned with our values we used the enumerate
keyword
Adding elements to a Dictionary
We can add elements by updating the dictionary with a new key and then assigning the value to a new key
We can even use the update
method to combine two different dictionaries
Delete elements of a dictionary
We can use the del
method to delete any key or value pair
The disadvantage of del
method is that it gives KeyError if you try to delete a nonexistent key, therefore we can use the pop
method.
This method takes in the key as the parameter. As a second argument, you can pass the default value if the key is not present.
Try to delete a nonexistent key. This will return None as None is given as the default value
Dictionary Methods
We can check whether our required key is present or not using the has_key
method
A dictionary in Python doesn't maintain any order
Last updated