Dictionaries in python
Dictionaries are useful to acess elemts using keys instead of keys,here keys are replaced by the index.
syntax:
variable_name = {
'key1' : 'element1',
'key2' : 'element',
...
'keyN' : 'elementN',
}
example:
roll = {
'alex' : '1WERG678',
'john' : '1WERG672',
'tom' : '1WERG666',
}
{'alex': '1WERG678', 'john': '1WERG672', 'tom': '1WERG666'}
Accessing element using keys
we cant use index positions for dicitiories, because they may vary,
so we need to use keys for accessing the elemnts, If the specified key doesn’t exist, KeyError the
exception will be raised.
roll["alex"]
'1WERG678'
Adding and Modifying elements
we can add or modify existing element by using this syntax given below
dict_name[key] = value
roll["jessy"]="1WERG645" #created new element
roll["alex"]="1WERG679" #roll no of alex is change to 79 to 78
Deleting Elements in dictionary
we can delete any element from the dictory by using del method ,If the key doesn’t exist in the dictionary, KeyError
exception is raised.
del roll["alex"] #alex will be deleted
{'john': '1WERG672', 'tom': '1WERG666'}