September
24
Dictionary
Dictionary is a key value pair,mapping between a set of keys and a set of values.
Association of a key and a value is called key-value pair or an item.
Python dictionary is like hash in Perl, an instance of Hashtable class in Java or an instance of the Scripting.Dictionary object in Visual Basic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
>>> tmp_dict = {"key1":"value1", "key2":"value2"} # create a new dictionary with two elements and assign it to the variable tmp_dict >>> dmp_dict # Key1 is a key and its associated value value1 {'key1': 'value1', 'key2': 'value2'} >>> tmp_dict["key1"] # get access by key 'value1' >>> tmp_dict["key2"] 'value2' >>> tmp_dict["key3"] # If key is not there then you get KeyError Traceback (innermost last): File "", line 1, in ? keyError: key3 >>> tmp_dict["key1"]="value3" # modifying value of dictionary >>> dmp_dict {'key1': 'value3', 'key2': 'value2'} >>> dir(tmp_dict) # dir give list of all attributes of object ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] >>> >>> help(tmp_dict) # help generates its document as text on console Help on built-in function iteritems: iteritems(...) D.iteritems() -> an iterator over the (key, value) items of D >>> >>> tmp_dict.keys() # It will give you all the keys in list format ['key1','key2'] >>> tmp_dict.values() # It will give you all the values in list format ['value3','value2'] |
Key features of dictionaries
- dictionary can not have duplicate keys
- assigning new value to existing key will simply replace the old value
- dictionary value can be any datatype, within a single dictionary you can have multiple datatype as value
- dictionary key can be any immutable datatype
- del, will delete individual item from dictionary
- clear , will clear all the data and give you a empty dictionary
1 2 3 4 5 |
>>> >>> tmp_dict = {"key1":"value1", "key2":2,"key3":[1,2],"key4":(1,2),"key5":{"key6":"value6"}} >>> tmp_dict {'key3': [1, 2], 'key2': 2, 'key1': 'value1', 'key5': {'key6': 'value6'}, 'key4': (1, 2)} >>> |
Deleting Items From Dictionaries
Dictionary has two method to delete/clear the data
1 2 3 4 5 6 7 8 9 |
>>> >>> tmp_dict {'key3': 3, 'key2': 2, 'key1': 1} >>> del tmp_dict['key2'] >>> tmp_dict {'key3': 3, 'key1': 1} >>> tmp_dict.clear() >>> tmp_dict {} |