Dictionary In Python

                                     Dictionary In Python

Dictionary is nothing but a collection of key-value pair . In python  Dictionary is an unordered collection of data values, used to store data values like a map, which holds key:value pair.Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’. The working concept of Dictionary in python is similar to that of real world dictionary.Keys are unique within a dictionary while values may not be.

Creating a Dictionary:

  • An empty dictionary without any items is written with just two curly braces, like this: {}. 
          Example -:  nameage  = {} 
  • The key of a dictionary can be of any data type, but values may be repeated.
           Example-:  nameage = {'Name': 'George', 'Age':37}

Updating Dictionary 

  • We can update a dictionary by adding a new key-pair into it or by modifying existing value.

     Example-:    nameage['Age'] = 8
                       nameage['Country'] = 'Australia'                                                                                   
  • We can update the value of different data types.
  • We should add new key-value pair in sequential order that is , if we are updating a value and try to add a new key-value at same time, then first we should update the already defined key value of that dictionary after that we can add new key-value pair.

Delete Dictionary Elements

  • We can delete single element(key-value pair) or can clear entire dictionary .
  • We can also delete entire dictionary .  
          Example -:   del nameage['Name']    => It will delete all value with "Name" key.
                             nameage.clear()           =>  It will clear entire dictionary.
                             del nameage                =>  It  will delete dictionary itself.

 Built-in Functions:

  1.  cmp(dict1,dict2) : Its compares elements of both the dictionaries.
  2.  len(dict) : It counts the total number of elements(key-value pair) in dictionary.
  3.  str(dict)  : It converts dictionary into a printable string format.
  4.  dict.clear()  : It removes all elements of the dictionary.
  5.  dict.copy()  : It copies elements of dictionary into key-value pair. 
  6.  dict.keys()   : It returns all the keys of dictionary.
  7.  dict.values()  : It returns list of values of dictionary.



Dear readers all the contents of this article are written correctly in my knowledge . If any one find that there is some mistake ,  then kindly let me know through comment or through contact form.

Comments