Python: Data Collections - Dictionary
In a previous article, we looked at the features of the list data collection in Python. In this article we look at the dictionary collection type in Python. As in other languages, the dictionary is a list of key-value pairs and just like other variables in Python we do not explicitly need to define the data type of key and value. It is easy to do bulk updates in Python dictionaries using other dictionary objects, but unlike a list the slice(:) operator is not supported. Hence some bulk updates have to be done using a loop.
The following code snippets demonstrate how dictionaries are created, modified and deleted. Inline comments (starting with #) clarify the purpose of specific lines of code.
# Code for demonstration of Python Dictionary class DemoDictClass: # List Initialization def Initialize(self): # Dictionaries are defined between curly brackets '{}' self._dictStr={"One" : 1, "Two":2, "Three":3, "Four":4} self._dictNumber = {1:"One", 2:"Two", 3:"Three", 4:"Four"} # List Print - values at specific indexes def PrintInit(self): print("------ PrintInit"); #Loop to print all elements print("------ All key,value pairs") for key, value in self._dictStr.items(): print(key + "," + str(value)) #Single command to print all Keys print("------ All keys") print(self._dictStr.keys()) # Single command to print all values print("------ All values") print(self._dictStr.values()) print("String dictionary element with key 'One' :" + str(self._dictStr["One"])) print("String dictionary element with key 'Three' :" + str(self._dictStr["Three"])) print("Number dictionary element with key 2 :" + self._dictNumber[2]) print("Number dictionary element with key 4 :" + self._dictNumber[4]) # List Modify - Add def ModifyElements_Add(self): print("------ ModifyElements_Add"); # Add 4 elements directly self._dictNumber.update({5:"Five", 6:"Six", 7:"Seven", 8:"Eight"}) print("------ All values of dicNumber:",self._dictNumber.values()) # Add 4 elements through another dictionary localDict1 = {9:"Nine", 10:"Ten", 11:"Eleven", 12:"Twelve"} self._dictNumber.update(localDict1) print("------ All values of dicNumber:", self._dictNumber.values()) #Adding existing element has no impact self._dictNumber.update({9:"Nine"}) print("------ All values of dicNumber:", self._dictNumber.values()) # Add 8 elements by adding 2 dictionaries localDict2 = {13:"Thirteen", 14: "Fourteen", 15:"Fifteen", 16:"Sixteen"} localDict3 = {17: "Seventeen", 18: "Eighteen", 19:"Nineteen", 20:"Twenty"} #{**localDict2, **localDict3} will merge dictionaries self._dictNumber.update({**localDict2, **localDict3}); print("------ All values of dicNumber:", self._dictNumber.values()) # List Modify - Delete def ModifyElements_Delete(self): print("------ ModifyElements_Delete"); print("------ All values of dicNumber:", self._dictNumber.values()) # Delete 1 element with specified key self._dictNumber.pop(2) print("------ All values of dicNumber:", self._dictNumber.values()) # Delete 1 element with specified key - another way del self._dictNumber[5] print("------ All values of dicNumber:", self._dictNumber.values()) # Remove all elements of a dictionary self._newDictStr = self._dictStr.copy() # create a new memory copy of dictionary self._dictStr.clear() #Delete two more elements (in slices) print("------ All values of dicStr:", self._dictStr.values()) print("------ All values of newDicStr:", self._newDictStr.values()) # List Modify - Update def ModifyElements_Update(self): print("------ ModifyElements_Update"); print("------ All values of newDicStr:", self._newDictStr.values()) # Update element with key "One" self._newDictStr["One"]=10 print("------ All values of newDicStr:", self._newDictStr.values()) # Update using another dictionary dictTemp = {"Two": 20, "Three": 30, "Four": 40} self._newDictStr.update(dictTemp) print("------ All values of newDicStr:", self._newDictStr.values()) # Update dictionary to restore original values. Values with same key will be overwritten dictTemp = {"One":1, "Two": 2, "Three": 3, "Four": 4} self._newDictStr.update(dictTemp) print("------ All values of newDicStr:", self._newDictStr.values()) # Update values using a loop for k in self._newDictStr: #iterate through every key in k self._newDictStr[k] = self._newDictStr[k] * 10 print("------ All values of newDicStr:", self._newDictStr.values()) # Instantiate the class and call member functions ddc=DemoDictClass() ddc.Initialize() ddc.PrintInit() ddc.ModifyElements_Add() ddc.ModifyElements_Delete() ddc.ModifyElements_Update()
The output for the above code is:
------ PrintInit ------ All key,value pairs One,1 Two,2 Three,3 Four,4 ------ All keys dict_keys(['One', 'Two', 'Three', 'Four']) ------ All values dict_values([1, 2, 3, 4]) String dictionary element with key 'One' :1 String dictionary element with key 'Three' :3 Number dictionary element with key 2 :Two Number dictionary element with key 4 :Four ------ ModifyElements_Add ------ All values of dicNumber: dict_values(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight']) ------ All values of dicNumber: dict_values(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve']) ------ All values of dicNumber: dict_values(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve']) ------ All values of dicNumber: dict_values(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']) ------ ModifyElements_Delete ------ All values of dicNumber: dict_values(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']) ------ All values of dicNumber: dict_values(['One', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']) ------ All values of dicNumber: dict_values(['One', 'Three', 'Four', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty']) ------ All values of dicStr: dict_values([]) ------ All values of newDicStr: dict_values([1, 2, 3, 4]) ------ ModifyElements_Update ------ All values of newDicStr: dict_values([1, 2, 3, 4]) ------ All values of newDicStr: dict_values([10, 2, 3, 4]) ------ All values of newDicStr: dict_values([10, 20, 30, 40]) ------ All values of newDicStr: dict_values([1, 2, 3, 4]) ------ All values of newDicStr: dict_values([10, 20, 30, 40])
Comments
Post a Comment