Friday, 25 March 2016

Dictionary in Python with code examples


Introduction to dictionary:
In the Dictionary each key is separated from its value by a colon (:), and the  items are separated by commas, the dictionary is enclosed in curly braces.
The dictionary is empty when there are no items in it. It is represented with just two curly braces {}.
The keys are unique within a dictionary and values may not be unique. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
Accessing Values in Dictionary:
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −
if __name__ == '__main__':
   
    Ex_Dictionary = {'Name': 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
    print "Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
    print "Ex_Dictionary['Class']: ", Ex_Dictionary['Class']

The output of the above code is
Ex_Dictionary['Name']:  Sandy
Ex_Dictionary['Age']:  15
Ex_Dictionary['Class']:  tenth

When we try to access the val;ues with the key that is not availabele in the above diracoty the below error may get appeared

if __name__ == '__main__':
   
    Ex_Dictionary = {'Name': 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
    print "Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
    print "Ex_Dictionary['Class']: ", Ex_Dictionary['Class']
    print "Ex_Dictionary['Class1']: ", Ex_Dictionary['Class1']
The above code results as
Ex_Dictionary['Name']:  Sandy
Ex_Dictionary['Age']:  15
Ex_Dictionary['Class']:  tenth
Ex_Dictionary['Class1']:
Traceback (most recent call last):

   print "Ex_Dictionary['Class1']: ", Ex_Dictionary['Class1']
KeyError: 'Class1'
How to Update Dictionary:
It is possible to update a dictionary by adding a new entry or a key-value pair.
Let us see the below sample code
if __name__ == '__main__':
   
    Ex_Dictionary = {'Name': 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
   
    print  "Before Updating: Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
    Ex_Dictionary['Age'] = 10
    print "After Updating: Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
   
   
    print "Before Updating: Ex_Dictionary['Class']: ", Ex_Dictionary['Class']
    Ex_Dictionary['Class'] = 5
    print "After Updating: Ex_Dictionary['Class']: ", Ex_Dictionary['Class']
The result of the above code is
Ex_Dictionary['Name']:  Sandy
Before Updating: Ex_Dictionary['Age']:  15
After Updating: Ex_Dictionary['Age']:  10
Before Updating: Ex_Dictionary['Class']:  tenth
After Updating: Ex_Dictionary['Class']:  5

Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
if __name__ == '__main__':
   
    Ex_Dictionary = {'Name': 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
   
    print  "Before Deleting: Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
    del Ex_Dictionary['Age']
    print "After deleting: Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
   
   
    print "Before Updating: Ex_Dictionary['Class']: ", Ex_Dictionary['Class']
    Ex_Dictionary['Class'] = 5
    print "After Updating: Ex_Dictionary['Class']: ", Ex_Dictionary['Class']
This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −

Ex_Dictionary['Name']:  Sandy
Before Deleting: Ex_Dictionary['Age']:  15
After deleting: Ex_Dictionary['Age']:
Traceback (most recent call last):
     print "After deleting: Ex_Dictionary['Age']: ", Ex_Dictionary['Age']
KeyError: 'Age'

Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example −

if __name__ == '__main__':
   
    Ex_Dictionary = {'Name': 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
The output of the above code is
Ex_Dictionary['Name']:
 Sandy (b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:
if __name__ == '__main__':
   
    Ex_Dictionary = {['Name']: 'Sandy', 'Age': 15, 'Class': 'tenth'};

    print "Ex_Dictionary['Name']: ", Ex_Dictionary['Name']
    ]
The output of the above code is
Traceback (most recent call last):
Traceback (most recent call last):
    Ex_Dictionary = {['Name']: 'Sandy', 'Age': 15, 'Class': 'tenth'};

TypeError: unhashable type: 'list'

No comments: