Dictionary-II





Hello folks....!!!
Today Let us see the remaining methods associated with the dictionary in python.

How to remove a key-value pair ?

There are two ways to do this. One is using del keyword and another is pop(). Let us see both of them with example.

del keyword:

  • This keyword removes the specified key from the dictionary. 
  • The syntax is del dict_name[key].
  • The main problem with this method is that, if the key is not present in the dictionary, it raises exception.
  • Let us look at an example.

Here, the key 'age' was present, so it removed it from the dictionary. The key 'salary' is not in the given dictionary and thus it raises an exception.

pop() :
  • The pop() method removes the specified key and its value from the dictionary.
  • Its syntax is dict_name.pop(key,default_value).
  • Here the key to be deleted is the first argument and the next argument overcomes the above problem.
  • The second argument provides a way to define a default value to display if the specified key is not present in the dictionary.
  • For example :

Nested Dictionaries :

These are nothing but dictionaries within dictionaries. We all know that a dictionary has key-value pairs. Here for a key, the value will be another dictionary. 

When will such situation arise....?

When the information to be represented is deeper, ie., it has subdivisions.consider the following dictionary :

dict1={ 
    'name':{
        'first_name':'Steve',
        'last_name':'Jobs'
           },
    'age':23,
    'address':{
        'number':6,
        'Street':'Brigade st',
        'City':'Bangalore'
                }
}
Here, the name has two subdivisions namely first name and last name. The address has to be represented in three levels namely house number,street and city. Such a dictionary is called a nested dictionary.

How to access this kind of nested dictionaries ?

Imagine them as 2D arrays. Now if you want to access the last_name, then you have to write as dict1['name']['last_name']. For example :


Note that the key 'age' is accessed as usual, because its value is just an integer and not a dictionary.

Updating/assigning values in a nested dictionary:

Now consider the following example:
This is students records:
stu={
'x001':{'name':'Vinay','tam':78,'eng':88,'maths':65,'sci':90,'soc':83},
'x002':{'name':'Ria','tam':38,'eng':58,'maths':60,'sci':70,'soc'53},
'x003':{'name':'Kishore','tam':98,'eng':83,'maths':95,'sci':89,'soc':96},
}

This can be considered in a matrix format as :


  • Now for a nested dictionary, there are inner and outer keys. 
  • Here each roll number is the outer key to identify a student and each attribute on the top forms the inner keys. 
  • Thus a particular student's whole record can be accessed by writing : stu['x001']
  • To access/update particular student's particular information : for say we need to change Ria's 'sci' mark to 50, then write as : stu['x002']['sci']=50.

    Next Topic👉

    Comments