Auto AdSense

Saturday, 24 January 2015

Python Dictionary






  • Accessing Values in Dictionary:
    #!/usr/bin/python
    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    print "dict['Name']: ", dict['Name'];
    print "dict['Age']: ", dict['Age'];
  • Output
    dict['Name']: Zara
    dict['Age']: 7
  • Updating Dictionary:
    #!/usr/bin/python
    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    dict['Age'] = 8; # update existing entry
    dict['School'] = "DPS School"; # Add new entry


    print "dict['Age']: ", dict['Age'];
    print "dict['School']: ", dict['School'];
  • Output
    dict['Age']: 8
    dict['School']: DPS School
  • Delete Dictionary Elements:
    #!/usr/bin/python

    dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

    del dict['Name']; # remove entry with key 'Name'
    dict.clear(); # remove all entries in dict
    del dict ; # delete entire dictionary

    print "dict['Age']: ", dict['Age'];
    print "dict['School']: ", dict['School'];
  • Output
    This will produce following result. Note an exception raised, this is because after del dict dictionary does not exist any more:

    dict['Age']:
    Traceback (most recent call last):
    File "test.py", line 8, in < module >
    print "dict['Age']: ", dict['Age'];
    TypeError: 'type' object is unsubscriptable
  • Properties of 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. Following is a simple example:

    #!/usr/bin/python

    dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

    print "dict['Name']: ", dict['Name'];

    When the above code is executed, it produces following result:

    dict['Name']: Manni

    (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:

    #!/usr/bin/python

    dict = {['Name']: 'Zara', 'Age': 7};

    print "dict['Name']: ", dict['Name'];

    When the above code is executed, it produces following result:

    Traceback (most recent call last):
       File "test.py", line 3, in < module >
       dict = {['Name']: 'Zara', 'Age': 7};
    TypeError: list objects are unhashable

No comments:

Post a Comment