{"id":28032,"date":"2023-08-24T19:48:45","date_gmt":"2023-08-24T14:18:45","guid":{"rendered":"https:\/\/tocxten.com\/?page_id=28032"},"modified":"2023-08-24T21:34:01","modified_gmt":"2023-08-24T16:04:01","slug":"dictionaries","status":"publish","type":"page","link":"https:\/\/tocxten.com\/index.php\/dictionaries\/","title":{"rendered":"Dictionaries"},"content":{"rendered":"\n<p><strong>Topics Covered <\/strong>: The Dictionary Data Type, Pretty Printing, Using Data Structures to Model Real-World Things<\/p>\n\n\n\n<p>A dictionary is a collection of items that are <strong>unordered, changeable, and indexed<\/strong>. Dictionary items are made up of <strong>Key \u2013 Value pair<\/strong> and each key is separated from its value by a <strong>colon (: )<\/strong> and whole thing is enclosed in curly braces as illustrated in the following syntax:<\/p>\n\n\n\n<p><strong>Syntax<\/strong>: my_dict = {&#8216;key1&#8217;: &#8216;value1&#8242;,&#8217;key2&#8217;: &#8216;value2&#8242;,&#8217;key3&#8242;: value3&#8217;\u2026&#8217;keyn&#8217;: &#8216;valuen&#8217;}<\/p>\n\n\n\n<p><strong>Example: <\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_dict = { \r\n    \"brand\":\"Maruthi\",\r\n    \"Model\": \"Suzuki\",\r\n    \"Year\":2023\r\n}   \r\nprint(my_dict)\r\n#Output : \r\n{'brand': 'Maruthi', 'Model': 'Suzuki', 'Year': 2023}\r\n<\/code><\/pre>\n\n\n\n<p>Keys are <strong>unique<\/strong> within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an <strong>immutable<\/strong> data type such as strings, numbers, or tuples. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences and hence maintain no left-to right order.<\/p>\n\n\n\n<p>Dictionary is a mapping between a set of indices (called\u00a0<strong>keys)<\/strong>\u00a0and a set of\u00a0<strong>values<\/strong>. Each key maps a value. The association of a key and a value is called a <strong>key-value<\/strong> pair.<\/p>\n\n\n\n<p class=\"has-background has-large-font-size\" style=\"background:linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 48%)\"><strong>Creating Dictionaries:<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>Creating Empty Dictionary:<\/strong> Empty dictionaries can be created using curly braces and dict() function as illustrated below: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Creating Empty Dictionaries \r\ned1 = {}  # using curly braces\r\ned2 = dict() # using dict() function\r\nprint(ed1)\r\nprint(ed2)\r\n<strong>#Output<\/strong>:\r\n{}\r\n{}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dbe1e6;font-size:25px\"><strong>Creating<\/strong>\u00a0<strong>Dictionary with Multiple Elements: <\/strong><\/p>\n\n\n\n<p><strong>Dictionaries with multiple elements can be created using curly braces. Each element containing key value pair are separated by comma operator as illustrated below: <\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Creating dictionary with multiple elements \r\n<strong>dict1 <\/strong>= {\"Name\":\"Palguni\",\"USN\":\"4MCECSBS123\",\"Course\":  \"BE\",\"Branch\":\"CSBS\",\"SEM\":\"1\"}\r\nprint(<strong>dict1<\/strong>)\r\n\r\n<strong>#Output:<\/strong>\r\n{'Name': 'Palguni', 'USN': '4MCECSBS123', 'Course': 'BE', 'Branch': 'CSBS', 'SEM': '1'}\n\n<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Example 2 :<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>H=dict()\r\nH&#91;\"one\"]=\"keyboard\" \r\nH&#91;\"two\"]=\"Mouse\" \r\nH&#91;\"three\"]=\"printer\" \r\nH&#91;\"Four\"]=\"scanner\" \r\nprint(H)\r\n\r\n<strong>#Output:<\/strong>\r\n\r\n{'one': 'keyboard', 'two': 'Mouse', 'three': 'printer', 'Four': 'scanner'}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#ecf3f4;font-size:30px\"><strong>Accessing Values in Dictionary<\/strong><\/p>\n\n\n\n<p>To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>student = {\"Name\":\"Palguni\",\"USN\":\"4MCECSBS123\",\"Course\": \"BE\",\"Branch\":\"CSBS\",\"SEM\":\"1\"}\r\nprint(student&#91;\"Name\"])\r\nprint(student&#91;\"USN\"])\r\nprint(student&#91;\"Course\"])\r\nprint(student&#91;\"Branch\"])\r\nprint(student&#91;\"SEM\"])\r\n\r\n<strong>#Output <\/strong>\r\n\r\nPalguni\r\n4MCECSBS123\r\nBE\r\nCSBS\r\n1<\/code><\/pre>\n\n\n\n<p>If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows \u2013<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(student&#91;\"Age\"])\r\n# Output:\r\nKeyError: 'Age'\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d9dee1;font-size:30px\"><strong>Updating Dictionary<\/strong> <\/p>\n\n\n\n<p>Dictionary can be updated by adding a <em>new entry or a key-value pair, modifying an existing entry, or deleting an existing entry<\/em> as shown below in the simple example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>student = {\"Name\":\"Raju\",\"Class\":8}\r\nprint(student)\r\n#Output:\r\n{'Name': 'Raju', 'Class': 8}\r\n\r\nstudent&#91;\"Age\"] = 10\r\nstudent&#91;\"School\"] = \"Contextual International School\"\r\nprint(student)\r\n#Output:\r\n{'Name': 'Raju', 'Class': 8, 'Age': 10, 'School': 'Contextual International School'}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d5dbe4;font-size:30px\"><strong>Deleting Dictionary Elements<\/strong><\/p>\n\n\n\n<p>You can either remove individual dictionary elements or clear the entire contents of a dictionary.<\/p>\n\n\n\n<p>Consider a dictionary <strong>dictx<\/strong> as illustrated below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dictx = {'Name': 'Pala', 'Age': 7, 'Class': 'First'}\r\nprint(dictx)\r\n#Output: {'Name': 'Pala', 'Age': 7, 'Class': 'First'}\r\n<\/code><\/pre>\n\n\n\n<p>Following example illustrates the deletion of single element with key \u2018<strong>Name<\/strong>\u2019:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>del dictx&#91;'Name']; # remove entry with key 'Name'\r\nprint(dictx)\r\n#Output: {'Age': 7, 'Class': 'First'}\r\n<\/code><\/pre>\n\n\n\n<p>The <strong>clear()<\/strong> method can be used to delete all the elements of dictionary as illustrated below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dictx.clear()    # remove all entries in dict\r\nprint(dictx)\r\n#Output: {}\r\n<\/code><\/pre>\n\n\n\n<p>One can also delete the entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the\u00a0<strong>del<\/strong>\u00a0statement. Following is a simple example \u2013<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>del dictx        # delete entire dictionary\r\nprint(dictx)\r\n#Output: NameError: name 'dictx' is not defined\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#dadfe3;font-size:30px\"><strong>Properties of Dictionary Keys<\/strong><\/p>\n\n\n\n<p>Dictionary <strong>values<\/strong> have no restrictions, and they can be of any arbitrary object. Keys are <strong>immutable<\/strong> type with following properties:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li><strong>More than one entry per key is not allowed. When duplicate key is allowed the last assignment wins:<\/strong>    <\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>     dictX = {'Name':\"Raju\",'Age':16,\"Name\":\"Rahul\"}\n     print(dictX)\n     <strong>#Output:<\/strong> {'Name': 'Rahul', 'Age': 16}\n<\/code><\/pre>\n\n\n\n<p>2. <strong>Since keys are immutable, one can use strings , numbers, or tuples as <\/strong>       <strong>dictionary keys.<\/strong><\/p>\n\n\n\n<p class=\"has-text-align-left\"><\/p>\n\n\n\n<p class=\"has-background\" style=\"background-color:#d8dfe7;font-size:30px\"><strong>Python Dictionary items() method<\/strong><\/p>\n\n\n\n<p>It returns the content of dictionary as a list of key and value. The key and value pair<br>will be in the form of a tuple, which is not in any order.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong> dictionary. items()<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D={'1':'Sunday','1':'Monday','3':'Tuesday','4':'Wednesday'} \r\nD.keys()\r\n#Output:\r\ndict_keys(&#91;'1', '3', '4'])\r\n\r\nlist(D.keys())\r\n#Output:\r\n&#91;'1', '3', '4']\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e4ebee;font-size:30px\"><strong>Python Dictionary Values Method<\/strong><\/p>\n\n\n\n<p>It returns a list of values from <strong>key-value<\/strong> pairs in a dictionary, which is not in any order. However, if we call both the <strong>items()<\/strong> and <strong>values()<\/strong> method without changing the dictionary\u2019s contents between these two (items() and values()), Python guarantees that the order of the two results will be the same.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\nD.values()\r\n\r\n#Output:\r\ndict_values(&#91;'Rohan', 'Raju', 'Pallu', 'Pallavi', 'Deeksha'])\r\n\r\nlist(D.values())\r\n#Output:\r\n&#91;'Rohan', 'Raju', 'Pallu', 'Pallavi', 'Deeksha']\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e9eff2;font-size:30px\"><strong>Traversing Dictionary elements using for loop.<\/strong><\/p>\n\n\n\n<p><strong>In Python, you can traverse the elements of a dictionary using various methods. Here are a few common ways to iterate over dictionary elements.<\/strong><\/p>\n\n\n\n<p><strong>Example 1: Traversing Dictionary using keys<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\nfor i in D.keys():\r\n    print(i,\":\",D&#91;i])\r\n\r\n#Output:\r\n1 : Rohan\r\n2 : Raju\r\n3 : Pallu\r\n4 : Pallavi\r\n5 : Deeksha\r\n<\/code><\/pre>\n\n\n\n<p><strong>Example 2 : Traversing Dictionary using values<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\nfor i in D.values():\r\n    print(i)\r\n\r\n#Output:\r\nRohan\r\nRaju\r\nPallu\r\nPallavi\r\nDeeksha\r\n<\/code><\/pre>\n\n\n\n<p><strong>Example 3 : Traversing Dictionary using values<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\nfor i in D.items():\r\n    print(i)\r\n\r\n#Output:\r\n('1', 'Rohan')\r\n('2', 'Raju')\r\n('3', 'Pallu')\r\n('4', 'Pallavi')\r\n('5', 'Deeksha')\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e6eaec;font-size:30px\"><strong>Membership Operators with Dictionary<\/strong><\/p>\n\n\n\n<p><strong>Membership operators (in and not in) can be used to check for the presence or absence of keys in a dictionary. Here&#8217;s how you can use membership operators with dictionaries in Python:<\/strong><strong><\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Example 1: Checking whether a key or value exists in a dictionary <\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\n\"10\" in D.keys()\r\n#Output: False\r\n\r\nD = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\n\"2\" in D.keys()\r\n#Output:  True\r\n\r\nD = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\n\"Pallu\" in D.values()\r\n#Output: True\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Example 2:<\/strong> <strong>Check if a key does not exist in the dictionary<\/strong><\/p>\n\n\n\n<p>if  &#8220;key4&#8221; not in my_dict: <br>    print(&#8220;Key &#8216;key4&#8217; does not exist in the dictionary.&#8221;) <br><\/p>\n\n\n\n<p>To compare dictionaries in Python, you can use the equality operator (<strong>==<\/strong>) or the cmp() function. Here&#8217;s how you can compare dictionaries using these methods:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li class=\"has-medium-font-size\"><strong>Using the equality operator (==):<\/strong><\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>dict1 = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\ndict2 = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\n\r\nif dict1 == dict2:\r\n    print(\"The dictionaries are equal.\")\r\nelse:\r\n    print(\"The dictionaries are not equal.\")\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>2. Using the cmp( ) function (available in Python 2):<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dict1 = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\ndict2 = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\n\r\nif  cmp(dict1, dict2) == 0:\r\n     print(\"The dictionaries are equal.\")\r\nelse:\r\n     print(\"The dictionaries are not equal.\")\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e5e9ec;font-size:30px\"><strong>Merging dictionaries: An update ( )<\/strong><\/p>\n\n\n\n<p><strong>Syntax:<\/strong>&nbsp; <strong>Dic_name1.update (dic_name2)<\/strong><strong><\/strong><\/p>\n\n\n\n<p>In Python, you can merge dictionaries using the <strong>update()<\/strong> method. The <strong>update()<\/strong> method modifies the dictionary in place by adding <strong>key-value<\/strong> pairs from another dictionary. Here&#8217;s how you can use the <strong>update()<\/strong> method to merge dictionaries:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dict1 = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\ndict2 = {\"key3\": \"value3\", \"key4\": \"value4\"}\r\ndict1.update(dict2)\r\nprint(dict1)\r\n# Output: {\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\", \"key4\": \"value4\"}\r\n<\/code><\/pre>\n\n\n\n<p>In the example above, dict1.update(dict2) merges dict2 into dict1. The update() method adds all the key-value pairs from dict2 to dict1. If there are common keys between the dictionaries, the values from dict2 will <strong>overwrite<\/strong> the values in dict1 for those keys.<\/p>\n\n\n\n<p class=\"has-background has-large-font-size\" style=\"background-color:#e1e8ed\"><strong>len ()<\/strong><\/p>\n\n\n\n<p>This method returns the number of key-value pairs in the given dictionary.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','2':'Raju','3':'Pallu','4':'Pallavi','5':'Deeksha'}\r\nlen(D)\r\n# Output: 5\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e4edee;font-size:30px\"><strong>get() and setdefault() methods with dictionary.<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>get() method: <\/strong><\/p>\n\n\n\n<p>The get() method retrieves the value associated with a given key in the dictionary. It takes the key as the first argument and an optional second argument specifying a default value to return if the key is not found in the dictionary. Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_dict = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\nvalue1 = my_dict.get(\"key1\")\r\nprint(value1)  \t\t\t\t# Output: \"value1\"\r\nvalue3 = my_dict.get(\"key3\", \"default\")\r\nprint(value3)  \r\n\r\n# Output: \"default\" (since \"key3\" doesn't exist)\r\n<\/code><\/pre>\n\n\n\n<p>In the example above, my_dict.get(&#8220;key1&#8221;) returns the value associated with &#8220;key1&#8221;, which is &#8220;value1&#8221;. If the key &#8220;key3&#8221; doesn&#8217;t exist in the dictionary, my_dict.get(&#8220;key3&#8221;, &#8220;default&#8221;) returns the default value &#8220;default&#8221;.<\/p>\n\n\n\n<p><strong>Another Example: <\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>picnic_items = {'apples':5,'cups':2}\r\n'I am bringing ' + str(picnic_items.get('cups',0)) + ' cups'\r\n#Output: 'I am bringing 2 cups'\r\n\r\n'I am bringing ' + str(picnic_items.get('oranges',2)) + ' oranges'\r\n#Output:'I am bringing 2 oranges'\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>setdefault() method <\/strong>: <\/p>\n\n\n\n<p>The setdefault() method returns the value associated with a given key in the dictionary. If the key doesn&#8217;t exist, it adds the key with a default value to the dictionary.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_dict = {\"key1\": \"value1\", \"key2\": \"value2\"}\r\n\r\nvalue1 = my_dict.setdefault(\"key1\", \"default\")\r\nprint(value1)   \t\t\t\t# Output: \"value1\"\nvalue3 = my_dict.setdefault(\"key3\", \"default\")\r\nprint(value3)  \t\t\t\t# Output: \"default\"\r\n\r\nprint(my_dict)  \r\n# Output: {\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"default\"}\r\n\r\n<\/code><\/pre>\n\n\n\n<p><strong>Example\u00a0<\/strong>: Get the value of the \u201ccolor\u201d item, if the \u201ccolor\u201d item does not exist, insert \u201ccolor\u201d with the value \u201c<strong>silksilver<\/strong>\u201d:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>car = {\r\n  \"brand\": \"Hundai\",\r\n  \"model\": \"Creta\",\r\n  \"year\": 2020\r\n}\r\nx = car.setdefault(\"color\", \"silksilver\")\r\nprint(x)\r\n\r\n#Output: \r\nsilksilver\r\n\r\nx = car.setdefault(\"brand\", \"Maruthi\")\r\nprint(x)\r\n\r\n#Output: \r\nHundai\r\n\r\nx = car.setdefault(\"Price\",100000)\r\nprint(car)\r\n\r\n#Output:\r\n{'brand': 'Hundai', 'model': 'Creta', 'year': 2020, 'color': 'silksilver', 'Price': 100000}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e4e9ec;font-size:30px\"><strong>Converting a dictionary to a list of tuples<\/strong><\/p>\n\n\n\n<p>Dictionary have a method called <strong>items()<\/strong> that returns a list of tuples where each tuple is a key value pair.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>D = {'1':'Rohan','3':'Raju','4':'Pallu','2':'Pallavi','5':'Deeksha'}\r\nt = list(D.items())\r\nprint(t)\r\n\r\n#Output:\r\n&#91;('1', 'Rohan'), ('3', 'Raju'), ('4', 'Pallu'), ('2', 'Pallavi'), ('5', 'Deeksha')]\r\n\r\nt.sort()\r\nprint(t)\r\n\r\n#Output:\r\n&#91;('1', 'Rohan'), ('2', 'Pallavi'), ('3', 'Raju'), ('4', 'Pallu'), ('5', 'Deeksha')]\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e8ecf0;font-size:30px\"><strong>Pretty Printing<\/strong><\/p>\n\n\n\n<p>In Python, the pprint module provides two functions for pretty-printing data structures: <strong>pprint() and pformat()<\/strong>. These functions are useful when you want to display complex data structures, such as dictionaries or lists, in a more readable and structured format. Here&#8217;s an explanation of <strong>pprint.pprint() and pprint.pformat()<\/strong> with examples:<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li class=\"has-medium-font-size\"><strong>pprint() function:<\/strong><strong><\/strong><\/li>\n<\/ol>\n\n\n\n<p>The <strong>pprint()<\/strong> function in the pprint module prints a data structure in a formatted and more readable manner. It accepts a single argument, which can be any data structure, such as a <strong>dictionary, list, or tuple<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># printing dictionary elements using print\r\nstudent_dict = {'Name':'Tyson',\r\n                'class':'XII',\r\n                'Address': {'Flat':1308,'Block':'A','Lane':2,'City':\"Hyderbad\"}}\r\nprint(student_dict)\r\n\r\n#Output:{'Name': 'Tyson', 'class': 'XII', 'Address': {'Flat': 1308, 'Block': 'A', 'Lane': 2, 'City': 'Hyderbad'}}\r\n\r\n# printing dictionary elements using pprint.pprint()\r\nimport pprint\r\npprint.pprint(student_dict)\r\n{'Address': {'Block': 'A', 'City': 'Hyderbad', 'Flat': 1308, 'Lane': 2},\r\n 'Name': 'Tyson',\r\n 'class': 'XII'}\r\n\r\n# printing dictionary elements using pprint.pprint() with width and indent\r\npprint.pprint(student_dict,width = 2, indent =2)\r\n\r\n{ 'Address': { 'Block': 'A',\r\n               'City': 'Hyderbad',\r\n               'Flat': 1308,\r\n               'Lane': 2},\r\n  'Name': 'Tyson',\r\n  'class': 'XII'}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\">2. <strong>pformat() function:<\/strong> <\/p>\n\n\n\n<p>The pformat() function in the pprint module returns a string representation of the data structure instead of printing it directly. This can be useful if you want to store or manipulate the formatted output.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x = pprint.pformat(student_dict,indent =5)\r\nprint(x)\r\n\r\n#Output\r\n{    'Address': {'Block': 'A', 'City': 'Hyderbad', 'Flat': 1308, 'Lane': 2},\r\n     'Name': 'Tyson',\r\n     'class': 'XII'}\r\n<\/code><\/pre>\n\n\n\n<p class=\"has-background\" style=\"background-color:#e1e7ec;font-size:25px\"><strong>Using Data Structures to Model Real-World Things<\/strong><strong> <\/strong><strong><\/strong><\/p>\n\n\n\n<p style=\"font-size:30px\"><strong>1. Using Data Structures to Model Chess: <\/strong><\/p>\n\n\n\n<p>In the realm of algebraic chess notation, the squares on the chessboard are denoted by a combination of numerical and alphabetical coordinates, exemplified in the diagram below:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"385\" height=\"381\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image.png\" alt=\"\" class=\"wp-image-28059\" srcset=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image.png 385w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-300x297.png 300w, https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-100x100.png 100w\" sizes=\"auto, (max-width: 385px) 100vw, 385px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"has-text-align-center\">Image Source : [1] <a href=\"https:\/\/automatetheboringstuff.com\/\">https:\/\/automatetheboringstuff.com\/<\/a><\/p>\n\n\n\n<p>Chess pieces are designated by specific letters: <strong>K<\/strong> for king, <strong>Q<\/strong> for queen, <strong>R<\/strong> for rook, <strong>B<\/strong> for bishop, and <strong>N<\/strong> for knight. Describing a move involves utilizing the letter of the piece along with the destination coordinates. A sequence of these moves portrays the events of a single turn (initiated by the white player). For example, annotation <strong>2. Nf3 Nc6<\/strong> signifies that, on the second turn of the game, the white player advanced a knight to <strong>f3<\/strong> and the black player moved a knight to <strong>c6<\/strong>.<\/p>\n\n\n\n<p>Algebraic chess notation serves as a standardized system for documenting chess movements. This system empowers players to articulate their moves using a blend of letters and numbers that symbolize the squares on the chessboard.<\/p>\n\n\n\n<p>The fundamental components of algebraic chess notation encompass:<\/p>\n\n\n\n<p><strong>K<\/strong>: King<\/p>\n\n\n\n<p><strong>Q<\/strong>: Queen<\/p>\n\n\n\n<p><strong>R<\/strong>: Rook<\/p>\n\n\n\n<p><strong>B<\/strong>: Bishop<\/p>\n\n\n\n<p><strong>N:<\/strong> Knight<\/p>\n\n\n\n<p><strong>No abbreviation<\/strong> for pawns<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Square Designation:<\/strong><\/p>\n\n\n\n<p>Each square on the chessboard is designated by a combination of a <strong>letter<\/strong> (column) and a <strong>number<\/strong> (row). The letters <strong>a-h<\/strong> represent the columns from <strong>left to right<\/strong>, and the numbers <strong>1-8<\/strong> represent the rows from <strong>bottom to top<\/strong>.<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Move Representation:<\/strong><\/p>\n\n\n\n<p>A move in algebraic notation typically consists of the piece abbreviation (if applicable), the destination square, and additional symbols to indicate the move type:<\/p>\n\n\n\n<p><strong>Pawn moves:<\/strong> Only the destination square is mentioned. If it&#8217;s a capture, the source file is indicated as well.<\/p>\n\n\n\n<p><strong>Example:<\/strong> e4, exd5 (e4 pawn moves to e5, capturing d5 pawn)<\/p>\n\n\n\n<p><strong>Other pieces:<\/strong> The piece abbreviation is followed by the destination square. If multiple pieces of the same type can move to the same square, the source file or rank is mentioned to disambiguate.<\/p>\n\n\n\n<p><strong>Example:<\/strong> Nf3 (Knight moves to f3), R1e5 (Rook on the first rank moves to e5)<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Special Moves:<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>Castling:<\/strong> <strong>O-O<\/strong> for kingside castling and <strong>O-O-O<\/strong> for queenside castling.<\/p>\n\n\n\n<p><strong>En Passant:<\/strong> If a pawn captures <strong>en<\/strong> passant, the destination square is indicated and &#8220;<strong>e.p.<\/strong>&#8221; is added.<\/p>\n\n\n\n<p><strong>Example:<\/strong> <strong>exd6 e.p<\/strong>. (e5 pawn captures d6 pawn en passant)<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Check and Checkmate:<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>&#8220;+&#8221;<\/strong> is added after a move to indicate a check.<\/p>\n\n\n\n<p><strong>&#8220;#&#8221;<\/strong> is added after a move to indicate a checkmate.<\/p>\n\n\n\n<p><strong>Example:<\/strong> <strong>Qh5+<\/strong> (Queen moves to <strong>h5<\/strong>, giving a check), <strong>Qh5#<\/strong> (Queen moves to <strong>h5<\/strong>, giving a checkmate)<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Other Symbols:<\/strong><strong><\/strong><\/p>\n\n\n\n<p>\u201c<strong>=<\/strong>\u201d is used to indicate pawn promotion. It is followed by the piece abbreviation to which the pawn promotes.<\/p>\n\n\n\n<p><strong>Example:<\/strong> <strong>e8=Q<\/strong> (Pawn on <strong>e8<\/strong> promotes to a Queen)<\/p>\n\n\n\n<p>By using algebraic chess notation, players can easily record and communicate their moves. It is also commonly used in chess literature, annotations, and online platforms for game analysis.<\/p>\n\n\n\n<p style=\"font-size:30px\"><strong> Using Data Structures to Model Tic-Tac-Toe<\/strong><\/p>\n\n\n\n<p>The configuration of a tic-tac-toe board resembles a sizable hash symbol (#), featuring nine compartments, each capable of holding an X, an O, or remaining unoccupied. When portraying the board utilizing a dictionary, a feasible approach involves assigning a unique string-based key to each slot, as depicted in the illustration below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"267\" height=\"260\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-1.png\" alt=\"\" class=\"wp-image-28061\"\/><\/figure>\n\n\n\n<p>Image Source : [1] <a href=\"https:\/\/automatetheboringstuff.com\/\">https:\/\/automatetheboringstuff.com\/<\/a><\/p>\n\n\n\n<p>Utilizing string representations, you can symbolize the contents of each slot on the board using <strong>&#8216;X<\/strong>&#8216;, <strong>&#8216;O&#8217;<\/strong>, or <strong>&#8216; &#8216;<\/strong> (a space character). Consequently, you will need to retain <strong>nine<\/strong> distinct strings. To achieve this, a suitable approach is to employ a dictionary comprising these string values. For instance, the string associated with the key <strong>&#8216;top-R<\/strong>&#8216; could indicate the top-right corner, the string linked to <strong>&#8216;low-L&#8217;<\/strong> could stand for the bottom-left corner, and similarly, the string correlated with <strong>&#8216;mid-M&#8217;<\/strong> could represent the middle section, and so forth. This dictionary constitutes a <strong>data structure<\/strong> that embodies the layout of a tic-tac-toe board. You can save this board-as-a-dictionary within a variable named <strong>theBoard<\/strong>.<\/p>\n\n\n\n<p><strong>theBoard <\/strong>= {&#8216;top-L&#8217;: &#8216; &#8216;, &#8216;top-M&#8217;: &#8216; &#8216;, &#8216;top-R&#8217;: &#8216; &#8216;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8216;mid-L&#8217;: &#8216; &#8216;, &#8216;mid-M&#8217;: &#8216; &#8216;, &#8216;mid-R&#8217;: &#8216; &#8216;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&#8216;low-L&#8217;: &#8216; &#8216;, &#8216;low-M&#8217;: &#8216; &#8216;, &#8216;low-R&#8217;: &#8216; &#8216;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<\/p>\n\n\n\n<p>The tic-tac-toe board depicted in the illustration below is represented by the data structure stored within the variable named <strong>theBoard<\/strong>:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"147\" height=\"126\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-2.png\" alt=\"\" class=\"wp-image-28062\"\/><\/figure>\n\n\n\n<p><strong>Fig<\/strong> : Empty Tic Tac Toe Board<\/p>\n\n\n\n<p>Given that each key&#8217;s value within <strong>theBoard<\/strong> variable is a single-space string, this dictionary delineates an entirely vacant board. In a scenario where player X takes the initiative and selects the middle space as their move, you can use this dictionary to represent the resulting board configuration:<\/p>\n\n\n\n<p><strong>theBoard<\/strong> = {&#8216;top-L&#8217;: &#8216; &#8216;, &#8216;top-M&#8217;: &#8216; &#8216;, &#8216;top-R&#8217;: &#8216; &#8216;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;mid-L&#8217;: &#8216; &#8216;, &#8216;mid-M&#8217;: &#8216;X&#8217;, &#8216;mid-R&#8217;: &#8216; &#8216;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;low-L&#8217;: &#8216; &#8216;, &#8216;low-M&#8217;: &#8216; &#8216;, &#8216;low-R&#8217;: &#8216; &#8216;}<\/p>\n\n\n\n<p>The data structure contained within the <strong>theBoard<\/strong> variable now corresponds to the tic-tac-toe board illustrated in the figure below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"169\" height=\"151\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-3.png\" alt=\"\" class=\"wp-image-28063\"\/><\/figure>\n\n\n\n<p><strong>Fig<\/strong>: The First Move<\/p>\n\n\n\n<p>An example of a board where player O emerges victorious by strategically placing <strong>Os across the top<\/strong> could resemble the following depiction:<\/p>\n\n\n\n<p><strong>theBoard<\/strong> = {&#8216;top-L&#8217;: &#8216;O&#8217;, &#8216;top-M&#8217;: &#8216;O&#8217;, &#8216;top-R&#8217;: &#8216;O&#8217;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;mid-L&#8217;: &#8216;X&#8217;, &#8216;mid-M&#8217;: &#8216;X&#8217;, &#8216;mid-R&#8217;: &#8216; &#8216;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;low-L&#8217;: &#8216; &#8216;, &#8216;low-M&#8217;: &#8216; &#8216;, &#8216;low-R&#8217;: &#8216;X&#8217;}<\/p>\n\n\n\n<p>The data structure stored in the theBoard variable currently reflects the tic-tac-toe board illustrated in the figure below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"137\" height=\"126\" src=\"https:\/\/tocxten.com\/wp-content\/uploads\/2023\/08\/image-4.png\" alt=\"\" class=\"wp-image-28064\"\/><\/figure>\n\n\n\n<p>Fig: Player O wins<\/p>\n\n\n\n<p style=\"font-size:30px\"><strong>Python Program to simulate the working of Tic-Tac-Toe:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-medium-font-size\"><code>theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',\r\n            'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',\r\n            'low-L': ' ', 'low-M': ' ', 'low-R': ' '}\r\n\r\ndef printBoard(board):\r\n    print(board&#91;'top-L'] + '|' + board&#91;'top-M'] + '|' + board&#91;'top-R'])\r\n    print('-+-+-')\r\n    print(board&#91;'mid-L'] + '|' + board&#91;'mid-M'] + '|' + board&#91;'mid-R'])\r\n    print('-+-+-')\r\n    print(board&#91;'low-L'] + '|' + board&#91;'low-M'] + '|' + board&#91;'low-R'])\r\n\r\nturn = 'X'\r\n\r\nfor i in range(9):\r\n    printBoard(theBoard)\r\n    print('Turn for ' + turn + '. Move on which space?')\r\n    move = input()\r\n    theBoard&#91;move] = turn\r\n    if turn == 'X':\r\n        turn = 'O'\r\n    else:\r\n        turn = 'X'\r\nprintBoard(theBoard)\r\n\r\n\r\n<strong># OutPut : <\/strong>\r\n| |\r\n-+-+-\r\n| |\r\n-+-+-\r\n| |\r\nTurn for X. Move on which space?\r\nmid-M\r\n| |\r\n-+-+-\r\n|X|\r\n-+-+-\r\n| |\r\nTurn for O. Move on which space?\r\nlow-L\r\n| |\r\n-+-+-\r\n|X|\r\n-+-+-\r\nO| |\r\n--snip--\r\nO|O|X\r\n-+-+-\r\nX|X|O\r\n-+-+-\r\nO| |X\r\nTurn for X. Move on which space?\r\nlow-M\r\nO|O|X\r\n-+-+-\r\nX|X|O\r\n-+-+-\r\nO|X|X\r\n<\/code><\/pre>\n\n\n\n<p>This isn\u2019t a complete <strong>tic-tac-toe game<\/strong>\u2014for instance, it doesn\u2019t ever check whether a player has won\u2014but it\u2019s enough to see <strong>how data structures can be used in programs<\/strong>.<\/p>\n\n\n\n<p style=\"font-size:30px\"><strong>Nested Dictionaries and Lists<\/strong><strong><\/strong><\/p>\n\n\n\n<p><strong>1. Nested Dictionaries: <\/strong>A nested dictionary is a dictionary that contains other dictionaries as its values. It allows you to create a hierarchical structure to organize and store data. Each inner dictionary can have its own set of key-value pairs. Here&#8217;s an example:<\/p>\n\n\n\n<p>student = {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; &#8216;name&#8217;: &#8216;John&#8217;,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; &#8216;age&#8217;: 20,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; &#8216;grades&#8217;: {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&#8216;math&#8217;: 90,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;science&#8217;: 85,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &#8216;history&#8217;: 95<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>In the example above, the student dictionary has three <strong>key-value<\/strong> pairs. The &#8216;grades&#8217; key has a value of another dictionary, which contains subject-grade pairs.<\/p>\n\n\n\n<p>You can access the nested values by chaining the keys together. For example, to access the math grade, you can use student[&#8216;grades&#8217;][&#8216;math&#8217;], which will return 90.<\/p>\n\n\n\n<p><strong>2. Nested Lists:<\/strong> A nested list is a list that contains other lists as its elements. It allows you to create a multidimensional structure to store data. Each inner list can have its own set of elements. Here&#8217;s an example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>matrix = &#91;\r\n    &#91;1, 2, 3],\r\n    &#91;4, 5, 6],\r\n    &#91;7, 8, 9]\r\n]\r\n<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p>In the example above, the matrix list contains three inner lists, forming a 3&#215;3 matrix. You can access the elements of the nested list using indexing. For example, to access the element 5, you can use matrix[1][1], which corresponds to the second row and second column. Nested lists can be useful for representing grids, matrices, or any other data structures that require multiple dimensions.<\/p>\n\n\n\n<p>Nested dictionaries and lists can be combined to create more complex data structures. For example, you can have a list of dictionaries, where each dictionary represents an entity with multiple properties, or you can have a dictionary that contains lists as its values, allowing you to group related items together.<\/p>\n\n\n\n<p>Remember that when working with nested data structures, you need to carefully consider the structure and access patterns to ensure efficient and correct data manipulation.<\/p>\n\n\n\n<p><br><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Topics Covered : The Dictionary Data Type, Pretty Printing, Using Data Structures to Model Real-World Things A dictionary is a collection of items that are unordered, changeable, and indexed. Dictionary&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":"","_links_to":"","_links_to_target":""},"class_list":["post-28032","page","type-page","status-publish","hentry"],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/28032","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/comments?post=28032"}],"version-history":[{"count":22,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/28032\/revisions"}],"predecessor-version":[{"id":28078,"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/pages\/28032\/revisions\/28078"}],"wp:attachment":[{"href":"https:\/\/tocxten.com\/index.php\/wp-json\/wp\/v2\/media?parent=28032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}