Python dictionary (Dictionary)
A dictionary is a mutable container model that can store objects of any type.
Each key -value key=>value pair, separated by a colon :
Separate each key-value pair with a comma ,
The entire dictionary is enclosed in curly braces {} in the following format:
d = {key1 : value1, key2 : value2 }
create
>>>dict = {'a': 1, 'b': 2, 'b': '3'};
>>> dict['b']
'3'
>>> dict
{'a': 1, 'b': '3'}
access
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
output
Revise
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
delete
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # delete entry whose key is 'Name'
dict.clear(); # clear all dictionary entries
del dict ; # delete dictionary
Features of the dictionary:
Two appearances of the same key are not allowed. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
Only output the latter Manni
Keys must be immutable, so they can be numbers, strings, or tuples, but not lists, as in the following example:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];