PYTHON PROGRAMMING (2010)
Pythons dictionary
Dictionary is a container type facility that is used to save or contain various objects or data. General syntax for dictionary is as follows.
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
A dictionary can be created as follows.
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
Accessing value in dictionary
To access a data or element one has to use the square brackets and the key value.
Example
#!/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
Used to modify or add a new existing entry.
Example
#!/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
It is used to remove the selected dictionary element or the entire data in dictionary elements.
Example
#!/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'];
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable.
Built in dictionary functions and methods
· cmp(di1, di2)- This is to compares elements of both di.
· len(di)- This provide the total length of the di which would be equal to the number of items in the di.
· str(di)- This produces a printable string representation of a di (dictionary).
· type(variable)- This returns the type of a pass variable and also If pass variable is di, then it would return a di type.
Example
#!/usr/bin/python
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" % cmp (dict1, dict2)
print "Return Value : %d" % cmp (dict2, dict3)
print "Return Value : %d" % cmp (dict1, dict)
Output
Return Value : -1
Return Value : 1
Return Value : 0