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{...}
>>> osint = {'name': 'Akash', 'age': 20, 'Country':'India'}
>>> type(osint)
<class 'dict'>
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
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> print(osint['country'])
India
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
>>> osint = {'name': 'Akash'}
>>> print(osint.get(name))
Akash
>>> print(osint.get('age', 20)
20
------------------------------------
>>> print(osint['age'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: age
Looping over Dictionary
Pre-requisites are the basics of looping statements and keywords such as for
and in
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> for key,value in osint.items():
... print("key is: %s" % key)
... print("value is: %s % value)
... print("---------------------")
...
key is: age
value is: 20
Here arises a question, why can't we use the keyword enumerate(osint)
instead of osint.items()
and here is the reason
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> for key,value in enumerate(osint):
... print("key is: %s" % key)
... print("value is: %s" % value)
...
key is: 0
value is: name
key is: 1
value is: age
key is: 2
value is country
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
>>> osint = {}
>>> osint["name"] = "Akash"
>>> print(osint)
{"name":"Akash"}
>>> osint["age"] = 20
>>> osint["country"] = "India"
>>> print(osint)
{'name': 'Akash', 'age': 20, 'country':'India'}
We can even use the update
method to combine two different dictionaries
>>> osint = {'name':'Akash'}
>>> favfood = {'food':'pizza'}
>>> osint.update(favfood)
>>> print(osint)
{'name':'Akash','food':'pizza'}
Delete elements of a dictionary
We can use the del
method to delete any key or value pair
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> del osint['age']
>>> print(osint)
{'name': 'Akash', 'country':'India'}
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.
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> print(osint.pop('country',None))
India
>>> print(osint)
{'name': 'Akash', 'age': 20}
Try to delete a nonexistent key. This will return None as None is given as the default value
>>> print(osint.pop("country",None)
None
Dictionary Methods
We can check whether our required key is present or not using the has_key
method
>>> osint = {'name': 'Akash', 'age': 20, 'country':'India'}
>>> osint.has_key('age')
True
>>> osint.has_key('food')
False
A dictionary in Python doesn't maintain any order
>>> names = {'akash': 1, 'vishnu': 2}
>>> names['linus'] = 3
>>> print(names)
{'linus': 3, 'akash': 1, 'vishnu': 2}
Last updated