{"id":3552,"date":"2020-05-17T05:08:04","date_gmt":"2020-05-17T05:08:04","guid":{"rendered":"https:\/\/www.staging6.machinelearningplus.com\/?p=3552"},"modified":"2021-05-27T09:11:50","modified_gmt":"2021-05-27T09:11:50","slug":"python-collections-guide","status":"publish","type":"page","link":"https:\/\/machinelearningplus.com\/python-collections-guide\/","title":{"rendered":"Python Collections &#8211; An Introductory Guide"},"content":{"rendered":"<p><em>Collections is a built-in python module that provides useful container datatypes. Container datatypes allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.<\/em> <\/p>\n<p>In this article, I will walk you through the different data structures supported by <code>collections<\/code> module, understand when to use them with examples.<\/p>\n<h2 id=\"contents\">Contents<\/h2>\n<ol>\n<li>namedtuple<\/li>\n<ul>\n<li>What is namedtuple<\/li>\n<li>Another way of creating a namedtuple<\/li>\n<li>Why use namedtuple over dictionary<\/li>\n<li>Creating a namedtuple from a python Dictionary<\/li>\n<li>How to replace a attribute in a namedtuple<\/li>\n<\/ul>\n<li>Counter<\/li>\n<li>defaultdict<\/li>\n<li>OrderedDict<\/li>\n<ul>\n<li>What happens when you delete and re-insert keys in OrderedDict<\/li>\n<li>Sorting with OrderedDict<\/li>\n<\/ul>\n<li>ChainMap<\/li>\n<ul>\n<li>What happens when we have redundant keys in a ChainMap<\/li>\n<li>How to add a new dictionary to a ChainMap<\/li>\n<li>How to reverse the order of dictionaries in a ChainMap<\/li>\n<\/ul>\n<li>UserList<\/li>\n<li>UserString<\/li>\n<li>UserDict<\/li>\n<\/ol>\n<pre><code class=\"python language-python\"># Import the collections module\nimport collections\n<\/code><\/pre>\n<p>Let us start with the <code>namedtuple<\/code><\/p>\n<h2 id=\"whatisnamedtuple\">What is namedtuple()<\/h2>\n<p>You can think of <code>namedtuple<\/code> in two ways:<\/p>\n<p>As an enhanced version of tuple. Or as a quick way of creating a python <code>class<\/code> with certain named attributes.<\/p>\n<p>A key difference between a <code>tuple<\/code> and a <code>namedtuple<\/code> is: while a <code>tuple<\/code> let&#8217;s you access data through indices, with a <code>namedtuple<\/code> you can access the elements with their names. <\/p>\n<p>You can actually define what all attributes a <code>namedtuple<\/code> can hold and create multiple instances of it. Just like how you would do with classes.<\/p>\n<p>So, in terms of functionality, its more similar to a <code>class<\/code>, eventhough it has <code>tuple<\/code> in its name. <\/p>\n<p>Let&#8217;s create a <code>namedtuple<\/code> that represents a &#8216;movie&#8217; with the attributes &#8216;genre&#8217;, &#8216;rating&#8217; and &#8216;lead_actor&#8217;.<\/p>\n<pre><code class=\"python language-python\"># Creating a namedtuple. \n\n# The field values are passed as a string seperated by ' '\nfrom collections import namedtuple\nmovie = namedtuple('movie','genre rating lead_actor')\n\n# Create instances of movie\nironman = movie(genre='action',rating=8.5,lead_actor='robert downey junior')\ntitanic = movie(genre='romance',rating=8,lead_actor='leonardo dicaprio')\nseven   = movie(genre='crime',rating=9,lead_actor='Brad Pitt')\n<\/code><\/pre>\n<p>Now, you can access any details of a movie you want using the identifier. It&#8217;s quite convenient and user friendly.<\/p>\n<pre><code class=\"python language-python\"># Access the fields\nprint(titanic.genre)\nprint(seven.lead_actor)\nprint(ironman.rating)\n<\/code><\/pre>\n<pre><code>\n#&gt; romance\n#&gt; Brad Pitt\n#&gt; 8.5\n<\/code><\/pre>\n<h4 id=\"anotherwayofcreatinganamedtuple\">Another way of creating a <code>namedtuple<\/code><\/h4>\n<p>Alternately, you can pass a list of field names instead of the filed names separated by a space.<\/p>\n<p>Let us see an example.<\/p>\n<pre><code class=\"python language-python\"># Creating namedtuple by passing fieldnames as a list of strings\nbook = namedtuple('book',['price','no_of_pages','author'])\n\nharry_potter = book('500','367','JK ROWLING')\npride_and_prejudice = book('300','200','jane_austen')\ntale = book('199','250','christie')\n\nprint('Price of pride and prejudice is ',pride_and_prejudice.price)\nprint('author of harry potter is',harry_potter.author)\n<\/code><\/pre>\n<pre><code>\n#&gt; Price of pride and prejudice is  300\n#&gt; author of harry potter is JK ROWLING\n<\/code><\/pre>\n<p>The items in a <code>namedtuple<\/code> can be accessed by both index as well as an identifier.<\/p>\n<pre><code class=\"python language-python\">print(tale[1])\n<\/code><\/pre>\n<pre><code>\n#&gt; 250\n<\/code><\/pre>\n<h2 id=\"whyusenamedtupleoverdictionary\">Why  use namedtuple over dictionary<\/h2>\n<p>A major advantage of <code>namedtuple<\/code> is they take up less space \/ memory than an equivalent dictionary. <\/p>\n<p>So, in the case of large data, namedtuples are efficient.<\/p>\n<p>I&#8217;ll demonstrate the same in below example.<\/p>\n<pre><code class=\"python language-python\"># Create a dict and namedtuple with same data and compare the size\nimport random\nimport sys\n\n# Create Dict\ndicts = {'numbers_1': random.randint(0, 10000),'numbers_2':random.randint(5000,10000)} \nprint('Size or space occupied by dictionary',sys.getsizeof(dicts))\n\n# converting same dictionary to a namedtuple\ndata=namedtuple('data',['numbers_1','numbers_2'])\nmy_namedtuple= data(**dicts)\nprint('Size or space occupied by namedtuple',sys.getsizeof(my_namedtuple))\n<\/code><\/pre>\n<pre><code>\n#&gt; Size or space occupied by dictionary 240\n#&gt; Size or space occupied by namedtuple 64\n<\/code><\/pre>\n<p>Executing above code, you find that namedtuple has size &#8217;64&#8217;, whereas a dictionary occupies much larger &#8216;240&#8217; bytes. That&#8217;s nearly 4x smaller memory.<\/p>\n<p>You can imagine the effect when expanded to handle a large number of such objects.<\/p>\n<h3 id=\"creatinganamedtuplefromapythondictionary\">Creating a <code>namedtuple<\/code> from a python Dictionary<\/h3>\n<p>Did you notice how we converted a dictionary into a namedtuple using <code>**<\/code> operator? <\/p>\n<p>All you need to do is: first define the structure of the <code>namedtuple<\/code> and pass the dictionary (<code>**dict<\/code>) to that <code>namedtuple<\/code> as argument. Only requirement is, the key&#8217;s of the <code>dict<\/code> should match the field names of the <code>namedtuple<\/code>.<\/p>\n<pre><code class=\"python language-python\"># Convert a dictionary into a namedtuple\ndictionary=dict({'price':567,'no_of_pages':878,'author': 'cathy thomas'})\n\n# Convert\nbook = namedtuple('book',['price','no_of_pages','author'])\nprint(book(**dictionary))\n<\/code><\/pre>\n<pre><code>\n#&gt; book(price=567, no_of_pages=878, author='cathy thomas')\n<\/code><\/pre>\n<h3 id=\"howtoreplaceaattributeinanamedtuple\">How to replace a attribute in a namedtuple<\/h3>\n<p>What if the value of one attribute has to be changed?<\/p>\n<p>You need to update it in the data. It can be done simply using <code>._replace()<\/code> method<\/p>\n<pre><code class=\"python language-python\"># update the price of the book\nmy_book=book('250','500','abc')\nmy_book._replace(price=300)\n\nprint(\"Book Price:\", my_book.price)\n<\/code><\/pre>\n<pre><code>\n#&gt; Book Price: 250\n<\/code><\/pre>\n<h2 id=\"counter\">Counter<\/h2>\n<p>A <code>counter<\/code> object is provided by the <code>collections<\/code> library.<\/p>\n<p>You have a list of some random numbers. What if you want to know how many times each number occurs?<\/p>\n<p><code>Counter<\/code> allows you to compute the frequency easily. It works not just for numbers but for any iterable object, like strings and lists.<\/p>\n<p>Counter is <code>dict<\/code> subclass, used to count hashable objects.<\/p>\n<p>It returns a dictionary with the elements as keys and the count (no of times the element was present) as values .<\/p>\n<p>EXAMPLES<\/p>\n<pre><code class=\"python language-python\">#importing Counter from collections\nfrom collections import Counter\n\nnumbers = [4,5,5,2,22,2,2,1,8,9,7,7]\nnum_counter = Counter(numbers)\nprint(num_counter)\n<\/code><\/pre>\n<pre><code>\n#&gt;Counter({2: 3, 5: 2, 7: 2, 4: 1, 22: 1, 1: 1, 8: 1, 9: 1})\n<\/code><\/pre>\n<p>Let&#8217;s use Counter to find the frequency of each character in a string<\/p>\n<pre><code class=\"python language-python\">#counter with strings\nstring = 'lalalalandismagic'\nstring_count = Counter(string)\nprint(string_count)\n<\/code><\/pre>\n<pre><code>\n#&gt; Counter({'a': 5, 'l': 4, 'i': 2, 'n': 1, 'd': 1, 's': 1, 'm': 1, 'g': 1, 'c': 1})\n<\/code><\/pre>\n<p>As you saw, we can view what elements are there and their count in a list string. <\/p>\n<p>In case you have a sentence and you want to view count of the words, how to do it?<\/p>\n<p>Use the <code>split()<\/code> function to make a list of words in the sentence and pass it to <code>Counter()<\/code><\/p>\n<pre><code class=\"python language-python\"># Using counter on sentences\nline = 'he told her that her presentation was not that good'\n\nlist_of_words = line.split() \nline_count=Counter(list_of_words)\nprint(line_count)\n<\/code><\/pre>\n<pre><code>\n#&gt; Counter({'her': 2, 'that': 2, 'he': 1, 'told': 1, 'presentation': 1, 'was': 1, 'not': 1, 'good': 1})\n<\/code><\/pre>\n<h3 id=\"howtofindmostcommonelementsusingcounter\">How to find most common elements using Counter<\/h3>\n<p>Counter  is very  useful in real life applications.<\/p>\n<p>Especially when you need to process large data, and you want to find out the frequency of some elements. Let me show some very useful methods using Counters.<\/p>\n<p><code>Counter().most_common([n])<\/code><\/p>\n<p>This returns a list of &#8216;n most common elements&#8217; along with their counts in descending order<\/p>\n<pre><code class=\"python language-python\"># Passing different values of n to most_common() function\nprint('The 2 most common elements in `numbers` are', Counter(numbers).most_common(2))\nprint('The 3 most common elements in `string` are', Counter(string).most_common(3))\n<\/code><\/pre>\n<pre><code>\n#&gt; The 2 most common elements in `numbers` are [(2, 3), (5, 2)]\n#&gt; The 3 most common elements in `string` are [('a', 5), ('l', 4), ('i', 2)]\n<\/code><\/pre>\n<p>The <code>most_common()<\/code> method can be used to print the most repetitive item. It is used in frequency analysis.<\/p>\n<pre><code class=\"python language-python\">Counter(list_of_words).most_common(1)\n<\/code><\/pre>\n<pre><code>\n#&gt; [('her', 2)]\n<\/code><\/pre>\n<p>We can use to the same to find the most repetitive character in a string.<\/p>\n<pre><code class=\"python language-python\">Counter(string).most_common(3)\n<\/code><\/pre>\n<pre><code>\n#&gt; [('a', 5), ('l', 4), ('i', 2)]\n<\/code><\/pre>\n<p>What happens if you don&#8217;t specify &#8216;n&#8217; while using <code>most_common(n)<\/code>?<\/p>\n<p>All the elements are their counts will be printed in descending order of their counts.<\/p>\n<pre><code class=\"python language-python\">Counter(string).most_common()\n<\/code><\/pre>\n<pre><code>\n#&gt;[('a', 5),('l', 4),('i', 2),('n', 1),('d', 1),('s', 1),('m', 1),('g', 1),('c', 1)]\n<\/code><\/pre>\n<p><code>Counter().elements()<\/code> method returns all the elements which have count greater than 0.<\/p>\n<pre><code class=\"python language-python\">print(sorted(string_count.elements()))\n<\/code><\/pre>\n<pre><code>\n#&gt; ['a', 'a', 'a', 'a', 'a', 'c', 'd', 'g', 'i', 'i', 'l', 'l', 'l', 'l', 'm', 'n', 's']\n<\/code><\/pre>\n<h2 id=\"defaultdict\">defaultdict<\/h2>\n<p>A dictionary is an unordered collection of keys and values. <\/p>\n<p>In the key: value pairs, the key should be distinct, and it cannot be changed. That is why in a dictionary, a list cannot be a key, as it is mutable. But, a tuple can be a key.<\/p>\n<pre><code class=\"python language-python\"># Dict with tuple as keys: OKAY\n{('key1', 'key2'): \"value\"}\n\n\n# Dict with list as keys: ERROR\n{['key1', 'key2']: \"value\"}\n<\/code><\/pre>\n<h3 id=\"howdefaultdictisdifferentfromdict\">How defaultdict is different from dict<\/h3>\n<p>If you try to access a key that is not present in a dictionary, it throws a <code>KeyError<\/code>. Whereas, in a <code>defaultdict<\/code> it does not give a <code>KeyError<\/code>.<\/p>\n<p>It does not give a keyerror . If you access a key that is not present,the <code>defaultdict<\/code> will return a default value.<\/p>\n<p>Syntax: <code>defaultdict(default_factory)<\/code><\/p>\n<p>When we access a key that is not present, <code>default_factory<\/code> function will return a default value <\/p>\n<pre><code class=\"python language-python\"># Creating a defaultdict and trying to access a key that is not present.\nfrom collections import defaultdict\ndef_dict = defaultdict(object)\ndef_dict['fruit'] = 'orange'\ndef_dict['drink'] = 'pepsi'\nprint(def_dict['chocolate'])\n<\/code><\/pre>\n<pre><code>\n#&gt; &amp;lt;object object at 0x7f591a2f4510&amp;gt;\n<\/code><\/pre>\n<p>If you excecute above command it does not give you a <code>KeyError<\/code>.<br \/>\nIn case you want to output that the value for the requested key is not present, you can define your own function and pass it to the defaultdict.<br \/>\nSee below example<\/p>\n<pre><code class=\"python language-python\"># Passing a function to return default value\ndef print_default():\n    return 'value absent'\n\ndef_dict=defaultdict(print_default)\nprint(def_dict['chocolate'])\n<\/code><\/pre>\n<pre><code>\n#&gt; value absent\n<\/code><\/pre>\n<p>In all other ways, it is the same as a normal dictionary. Same syntax commands are used for defaultdict too.<\/p>\n<p>Actually, it is possible to overcome the <code>KeyError<\/code> in dictionary by using the <code>get<\/code> method.<\/p>\n<pre><code class=\"python language-python\"># Make dict return a default value\nmydict = {'a': 'Apple', 'b': 'Ball'}\nmydict.get('c', 'NOT PRESENT')\n<\/code><\/pre>\n<pre><code>\n#&gt; 'NOT PRESENT'\n<\/code><\/pre>\n<h2 id=\"ordereddict\">OrderedDict<\/h2>\n<p>A dict is an UNORDERED collection of key value pairs. But, an <code>OrderedDict<\/code> maintains the ORDER in which the keys are inserted.<\/p>\n<p>It is subclass of <code>dict<\/code>.<\/p>\n<p>I am going to create a ordinary <code>dict<\/code> and make it <code>OrderedDict<\/code> to show you the difference<\/p>\n<pre><code class=\"python language-python\"># create a dict and print items\nvehicle = {'bicycle': 'hercules', 'car': 'Maruti', 'bike': ' Harley', 'scooter': 'bajaj'}\n\nprint('This is normal dict')\nfor key,value in vehicle.items():\n    print(key,value)\n\nprint('-------------------------------')\n\n# Create an OrderedDict and print items\nfrom collections import OrderedDict\nordered_vehicle=OrderedDict()\nordered_vehicle['bicycle']='hercules'\nordered_vehicle['car']='Maruti'\nordered_vehicle['bike']='Harley'\nprint('This is an ordered dict')\n\nfor key,value in ordered_vehicle.items():\n    print(key,value)\n<\/code><\/pre>\n<pre><code>\n#&gt; This is normal dict\n#&gt; bicycle hercules\n#&gt; car Maruti\n#&gt; bike  Harley\n#&gt; scooter bajaj\n-------------------------------\n#&gt; This is an ordered dict\n#&gt; bicycle hercules\n#&gt; car Maruti\n#&gt; bike Harley\n<\/code><\/pre>\n<p>In an <code>OrderedDict<\/code>, even after changing the value of certain keys, the order remains same or unchanged.<\/p>\n<pre><code class=\"python language-python\"># I have changed the value of car in this ordered dictionary.\nordered_vehicle['car']='BMW'# I have changed the value of car in this ordered dictionary.\nfor key,value in ordered_vehicle.items():\n    print(key,value)\n<\/code><\/pre>\n<pre><code>\n#&gt; bicycle hercules\n#&gt; car BMW\n#&gt; bike harley davison\n<\/code><\/pre>\n<h3 id=\"whathappenswhenyoudeleteandreinsertkeysinordereddict\">What happens when you delete and re-insert keys in OrderedDict<\/h3>\n<p>When a key is deleted, the information about its order is also deleted. When you re-insert the key, it is treated as a new entry and corresponding order information is stored.<\/p>\n<pre><code class=\"python language-python\"># deleting a key from an OrderedDict\nordered_vehicle.pop('bicycle')\nfor key,value in ordered_vehicle.items():\n    print(key,value)\n<\/code><\/pre>\n<pre><code>\n#&gt; car BMW\n#&gt; bike harley davison\n<\/code><\/pre>\n<p>On reinserting the key, it is considered as a new entry.<\/p>\n<pre><code class=\"python language-python\"># Reinserting the same key and print\nordered_vehicle['bicycle']='hercules'\nfor key,value in ordered_vehicle.items():\n    print(key,value)\n<\/code><\/pre>\n<pre><code>\n#&gt; car BMW\n#&gt; bike harley davison\n#&gt; bicycle hercules\n<\/code><\/pre>\n<p>You can see the bicycle is at the last, the order has changed when we deleted the key. <\/p>\n<p>There are several useful commands that can be executed. We can perform sorting functions as per need<\/p>\n<h3 id=\"sortingwithordereddict\">Sorting with OrderedDict<\/h3>\n<p>What if you want to sort the items in increasing order of their values? This will help you in data analysis<\/p>\n<p>Sort the items by KEY (in ascending order)<\/p>\n<pre><code class=\"python language-python\"># Sorting items in ascending order of their keys\ndrinks = {'coke':5,'apple juice':2,'pepsi':10}\nOrderedDict(sorted(drinks.items(), key=lambda t: t[0]))\n<\/code><\/pre>\n<pre><code>\n#&gt; OrderedDict([('apple juice', 2), ('coke', 5), ('pepsi', 10)])\n<\/code><\/pre>\n<p>Sort the pairs by VALUE (in ascending order)<\/p>\n<pre><code class=\"python language-python\">\n# Sorting according to values\nOrderedDict(sorted(drinks.items(), key=lambda t: t[1]))\n<\/code><\/pre>\n<pre><code>\n#&gt; OrderedDict([('apple juice', 2), ('coke', 5), ('pepsi', 10)])\n<\/code><\/pre>\n<p>Sort the dictionary by length of key string (in ascending order)<\/li>\n<pre><code class=\"python language-python\"># Sorting according to length of key string\nOrderedDict(sorted(drinks.items(), key=lambda t: len(t[0])))\n<\/code><\/pre>\n<pre><code>\n#&gt; OrderedDict([('coke', 5), ('pepsi', 10), ('apple juice', 2)])\n<\/code><\/pre>\n<h2 id=\"chainmap\">ChainMap<\/h2>\n<p>ChainMap is a container datatype which stores multiple dictionaries.<br \/>\nIn many cases, you might have relevant or similar dictionaries, you can store them collectively in a <code>ChainMap<\/code><\/p>\n<p>You can print all the items in a <code>ChainMap<\/code> using <code>.map<\/code> operator. Below code demonstrates the same<\/p>\n<pre><code class=\"python language-python\"># Creating a ChainMap from 3 dictionaries.\nfrom collections import ChainMap\ndic1={'red':5,'black':1,'white':2}\ndic2={'chennai':'tamil','delhi':'hindi'}\ndic3={'firstname':'bob','lastname':'mathews'}\n\nmy_chain = ChainMap(dic1,dic2,dic3)\nmy_chain.maps\n<\/code><\/pre>\n<pre><code>\n#&gt; [{'black': 1, 'red': 5, 'white': 2}, {'chennai': 'tamil', 'delhi': 'hindi'},{'firstname': 'bob', 'lastname': 'mathews'}]\n<\/code><\/pre>\n<p>You can print  keys of all dictionaries  in a chainmap using <code>.keys()<\/code> function<\/p>\n<pre><code class=\"python language-python\">print(list(my_chain.keys()))\n<\/code><\/pre>\n<pre><code>\n#&gt; ['firstname', 'lastname', 'chennai', 'delhi', 'red', 'black', 'white']\n<\/code><\/pre>\n<p>You can print the values  of all dictionaries in a chainmap using <code>.values()<\/code>function<\/p>\n<pre><code class=\"python language-python\">print(list(my_chain.values()))\n<\/code><\/pre>\n<pre><code>\n#&gt; ['bob', 'mathews', 'tamil', 'hindi', 5, 1, 2]\n<\/code><\/pre>\n<h3 id=\"whathappenswhenwehaveredundantkeysinachainmap\">What happens when we have redundant keys in a ChainMap<\/h3>\n<p>It is possible that 2 dictionaries might have the same key. See an example below.<\/p>\n<pre><code class=\"python language-python\"># Creating a chainmap whose dictionaries do not have unique keys\ndic1 = {'red':1,'white':4}\ndic2 = {'red':9,'black':8}\nchain = ChainMap(dic1,dic2)\nprint(list(chain.keys()))\n<\/code><\/pre>\n<pre><code>\n#&gt;['black', 'red', 'white']\n<\/code><\/pre>\n<p>Observe that &#8216;red&#8217; is not repeated, it is printed only once<\/p>\n<h3 id=\"howtoaddanewdictionarytoachainmap\">How to add a new dictionary to a ChainMap<\/h3>\n<p>You can add a new dictionary at the beginning of a ChainMap using <code>.new_child()<\/code> method. It is demonstrated in the below code. <\/p>\n<pre><code class=\"python language-python\"># Add a new dictionary to the chainmap through .new_child()\nprint('original chainmap', chain)\n\nnew_dic={'blue':10,'yellow':12} \nchain=chain.new_child(new_dic)\n\nprint('chainmap after adding new dictioanry',chain)\n<\/code><\/pre>\n<pre><code>\n#&gt; original chainmap ChainMap({'red': 1, 'white': 4}, {'red': 9, 'black': 8})\n#&gt; chainmap after adding new dictioanry ChainMap({'blue': 10, 'yellow': 12}, {'red': 1, 'white': 4}, {'red': 9, 'black': 8})\n<\/code><\/pre>\n<h3 id=\"howtoreversetheorderofdictionariesinachainmap\">How to reverse the order of dictionaries in a ChainMap<\/h3>\n<p>The order in which dictionaries are stored in a ChainMap can be reversed using <code>reversed()<\/code> function.<\/p>\n<pre><code class=\"python language-python\"># We are reversing the order of dictionaries using reversed() function\nprint('orginal chainmap',  chain)\n\nchain.maps = reversed(chain.maps)\nprint('reversed Chainmap', str(chain))\n<\/code><\/pre>\n<pre><code>\n#&gt; orginal chainmap ChainMap({'blue': 10, 'yellow': 12}, {'red': 1, 'white': 4}, {'red': 9, 'black': 8})\n#&gt;  reversed Chainmap ChainMap({'red': 9, 'black': 8}, {'red': 1, 'white': 4}, {'blue': 10, 'yellow': 12})\n<\/code><\/pre>\n<h2 id=\"userlist\">UserList<\/h2>\n<p>Hope you are familiar with python <code>list<\/code>s?. <\/p>\n<p>A <code>UserList<\/code> is list-like container datatype, which is wrapper class for <code>list<\/code>s.<\/p>\n<p>Syntax: <code>collections.UserList([list])<\/code><\/p>\n<p>You pass a normal list as an argument to userlist. This list is stored in the data attribute and can be accessed through <code>UserList.data<\/code> method.<\/p>\n<pre><code class=\"python language-python\"># Creating a user list with argument my_list\nfrom collections import UserList\nmy_list=[11,22,33,44]\n\n# Accessing it through `data` attribute\nuser_list=UserList(my_list)\nprint(user_list.data)\n<\/code><\/pre>\n<pre><code>\n#&gt; [11, 22, 33, 44]\n<\/code><\/pre>\n<h3 id=\"whatistheuseofuserlists\">What is the use of UserLists<\/h3>\n<p>Suppose you want to double all the elements in some particular lists as a reward. Or maybe you want to ensure that no element can be deleted from a given list.<\/p>\n<p>In such cases, we need to add a certain &#8216;behavior&#8217; to our lists, which can be done using UserLists. <\/p>\n<p>For example, Let me show you how <code>UserList<\/code> can be used to override the functionality of a built-in method. The below code prevents the addition of a new value (or appending) to a list.<\/p>\n<pre><code class=\"python language-python\"># Creating a userlist where adding new elements is not allowed.\n\nclass user_list(UserList):\n    # function to raise error while insertion\n    def append(self,s=None):\n        raise RuntimeError(\"Authority denied for new insertion\")\n\nmy_list=user_list([11,22,33,44])\n\n# trying to insert new element\nmy_list.append(55)\n<\/code><\/pre>\n<pre><code>\n#&gt; ---------------------------------------------------------------------------\n\nRuntimeError                              Traceback (most recent call last)\n\n&amp;lt;ipython-input-2-e8f22159f6e0&amp;gt; in &amp;lt;module&amp;gt;\n      4 \n      5 my_list=user_list([11,22,33,44])\n----&amp;gt; 6 my_list.append(55)\n      7 print(my_list)\n\n\n&amp;lt;ipython-input-2-e8f22159f6e0&amp;gt; in append(self, s)\n      1 class user_list(UserList):\n      2     def append(self,s=None):\n----&amp;gt; 3         raise RuntimeError(\"Authority denied for new insertion\")\n      4 \n      5 my_list=user_list([11,22,33,44])\n\n\nRuntimeError: Authority denied for new insertion\n<\/code><\/pre>\n<p>The above code prints <code>RunTimeError<\/code> message and does not allow appending. This can be helpful if you want to make sure nobody can insert their name after a particular deadline. So, <code>UserList<\/code> have very real time efficient.<\/p>\n<h2 id=\"userstring\">UserString<\/h2>\n<p>Just like <code>UserLists<\/code> are wrapper class for <code>list<\/code>s, <code>UserString<\/code> is a wrapper class for <code>string<\/code>s.<\/p>\n<p>It allows you to add certain functionality\/behavior to the string. You can pass any string convertible argument to this class and can access the string using the data attribute of the class.<\/p>\n<pre><code class=\"python language-python\"># import Userstring\nfrom collections import UserString\nnum=765\n\n# passing an string convertible argument to userdict\nuser_string = UserString(num)\n\n# accessing the string stored \nuser_string.data\n<\/code><\/pre>\n<pre><code>\n#&gt; '765'\n<\/code><\/pre>\n<p>As you can see in above example, the number 765 was converted into a string &#8216;765&#8217; and can be accessed through the <code>UserString.data<\/code> method.<\/p>\n<h3 id=\"howandwhenuserstringcanbeused\">How and when UserString can be used<\/h3>\n<p><code>UserString<\/code> can be used to modify the string, or perform certain funtions.<\/p>\n<p>What if you want to remove a particular word from a text file (wherever present)?<\/p>\n<p>May be, some words have misplaced and need to be removed. <\/p>\n<p>Let&#8217;s see an example of how `UserString` can be used to remove certain odd words from a string<\/p>\n<pre><code class=\"python language-python\"># Using UserString to remove odd words from the textfile\nclass user_string(UserString):\n\n    def append(self, new):\n        self.data = self.data + new\n\n    def remove(self, s):\n        self.data = self.data.replace(s, \"\")\n\ntext='apple orange grapes bananas pencil strawberry watermelon eraser'\nfruits = user_string(text)\n\nfor word in ['pencil','eraser']:\n    fruits.remove(word)\n\nprint(fruits)\n<\/code><\/pre>\n<pre><code>\n#&gt; apple orange grapes bananas  strawberry watermelon \n<\/code><\/pre>\n<p>You can see that &#8216;pencil&#8217; and &#8216;eraser&#8217; were removed using the function class <code>user_string<\/code>. <\/p>\n<p>Let us consider another case. What if you need to replace a word by some other word throughout the file?<\/p>\n<p><code>Userstring<\/code> makes this far easier as shown below.The below code replaces a certain word throughout the textfile using <code>UserString<\/code><\/p>\n<p>I have defined a function inside the class to replace certain word by &#8216;The Chairman&#8217; throughout.<\/p>\n<pre><code class=\"python language-python\"># using UserString to replace the name or a word throughout.\nclass user_string(UserString):\n\n    def append(self, new):\n        self.data = self.data + new\n\n    def replace(self,replace_text):\n        self.data = self.data.replace(replace_text,'The Chairman')\n\ntext = 'Rajesh concluded the meeting very late. Employees were disappointed with Rajesh'\ndocument = user_string(text)\n\ndocument.replace('Rajesh')\n\nprint(document.data)\n<\/code><\/pre>\n<pre><code>#&gt; The Chairman concluded the meeting very late. Employees were disappointed with The Chairman\n<\/code><\/pre>\n<p>As you can see, &#8216;Rajesh&#8217; is replaced with &#8216;The Chairman&#8217; everywhere. Similarly, UserStrings help you simplify all processes<\/p>\n<h2 id=\"userdict\">UserDict<\/h2>\n<p>It is a wrapper class for dictionaries. The syntax, functions are similar to UserList and UserString.<\/p>\n<p>syntax:<code>collections.UserDict([data])<\/code><\/p>\n<p>We pass a dictionary as the argument which is stored in the data attribute of UserDict.<\/p>\n<pre><code class=\"python language-python\"># importing UserDict\nfrom collections import UserDict \nmy_dict={'red':'5','white':2,'black':1} \n\n# Creating an UserDict \nuser_dict = UserDict(my_dict) \nprint(user_dict.data) \n<\/code><\/pre>\n<pre><code>\n#&gt; {'red': '5', 'white': 2, 'black': 1}\n<\/code><\/pre>\n<h3 id=\"howuserdictcanbeused\">How UserDict can be used<\/h3>\n<p><code>UserDict<\/code> allows you to create a dictionary modified to your needs. Let&#8217;s see an example of how UserDict can be used to override the functionality of a built-in method. The below code prevents a key-value pair from being dropped.<\/p>\n<pre><code class=\"python language-python\"># Creating a Dictionary where deletion of an  is not allowed \nclass user_dict(UserDict):       \n    # Function to stop delete\/pop\n    def pop(self, s = None):\n        raise RuntimeError(\"Not Authorised to delete\") \n\ndata = user_dict({'red':'5','white':2,'black':1}) \n\n# try to delete a item\ndata.pop(1)\n<\/code><\/pre>\n<pre><code>\n#&gt; ---------------------------------------------------------------------------\n\nRuntimeError                              Traceback (most recent call last)\n\n&amp;lt;ipython-input-16-2e576a68d2ad&amp;gt; in &amp;lt;module&amp;gt;\n     12 \n     13 #try to delete a item\n---&amp;gt; 14 data.pop(1)\n\n\n&amp;lt;ipython-input-16-2e576a68d2ad&amp;gt; in pop(self, s)\n      5         def pop(self, s = None):\n      6 \n----&amp;gt; 7             raise RuntimeError(\"Not Authorised to delete\")\n      8 \n      9 \n\n\nRuntimeError: Not Authorised to delete\n<\/code><\/pre>\n<p>You will receive an RunTimeError message. This will help if you don&#8217;t want to lose data.<\/p>\n<p>What if some keys have junk values and you need to replace them with nil or &#8216;0&#8217;? See the below examples on how to use Userdict for the same.<\/p>\n<pre><code class=\"python language-python\">class user_dict(UserDict): \n        def replace(self,key):\n            self[key]='0'\n\nfile= user_dict({'red':'5','white':2,'black':1,'blue':4567890}) \n\n# Delete 'blue' and 'yellow'\nfor i in ['blue','yellow']:\n    file.replace(i)\n\nprint(file)\n<\/code><\/pre>\n<pre><code>#&gt; {'red': '5', 'white': 2, 'black': 1, 'blue': '0', 'yellow': '0'}\n<\/code><\/pre>\n<p>The field with junk values have been replaced with 0. These are just simple examples of how an UserDict allows you to create a dictionary with required functionality<\/p>\n<p>These are all the container datatypes from the collections module. They increase efficiency by a great amount when used on large datasets.<\/p>\n<h2>Conclusion<\/h2>\n<p> I hope you have understood when and why to use the above container datatypes. If you have any questions, please drop it in the comments<\/p>\n<h2>Recommended Posts<\/h2>\n<p><a href=\"https:\/\/machinelearningplus.com\/python-json-guide\/\" rel=\"noopener noreferrer\" target=\"_blank\">Python JSON Guide<\/a><br \/>\n<a href=\"https:\/\/machinelearningplus.com\/python\/python-regex-tutorial-examples\/\" rel=\"noopener noreferrer\" target=\"_blank\">Python RegEx Tutorial<\/a><br \/>\n<a href=\"https:\/\/machinelearningplus.com\/python\/python-logging-guide\/\" rel=\"noopener noreferrer\" target=\"_blank\">Python Logging Guide <\/a><br \/>\n<a href=\"https:\/\/machinelearningplus.com\/python\/parallel-processing-python\/\" rel=\"noopener noreferrer\" target=\"_blank\">Paralel Processing in Python<\/a><\/p>\n<p>This article was contributed by <a href=\"https:\/\/machinelearningplus.com\/shrivarsheni\/\" rel=\"noopener noreferrer\" target=\"_blank\">Shrivarsheni<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Collections is a built-in python module that provides useful container datatypes. Container datatypes allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects. In this article, I will walk you through the different data structures [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":3551,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-3552","page","type-page","status-publish","has-post-thumbnail","hentry"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Collections - An Introductory Guide - machinelearningplus<\/title>\n<meta name=\"description\" content=\"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/localhost:8080\/python-collections-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Collections - An Introductory Guide - machinelearningplus\" \/>\n<meta property=\"og:description\" content=\"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/localhost:8080\/python-collections-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"machinelearningplus\" \/>\n<meta property=\"article:modified_time\" content=\"2021-05-27T09:11:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/localhost:8080\/wp-content\/uploads\/2020\/05\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1280\" \/>\n\t<meta property=\"og:image:height\" content=\"720\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"18 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/\",\"url\":\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/\",\"name\":\"Python Collections - An Introductory Guide - machinelearningplus\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2020\\\/05\\\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png\",\"datePublished\":\"2020-05-17T05:08:04+00:00\",\"dateModified\":\"2021-05-27T09:11:50+00:00\",\"description\":\"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/localhost:8080\\\/python-collections-guide\\\/#primaryimage\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2020\\\/05\\\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2020\\\/05\\\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png\",\"width\":1280,\"height\":720},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#website\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"name\":\"machinelearningplus\",\"description\":\"Learn Data Science (AI \\\/ ML) Online\",\"publisher\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/machinelearningplus.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#organization\",\"name\":\"machinelearningplus\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"contentUrl\":\"https:\\\/\\\/machinelearningplus.com\\\/wp-content\\\/uploads\\\/2022\\\/05\\\/MachineLearningplus-logo.svg\",\"width\":348,\"height\":36,\"caption\":\"machinelearningplus\"},\"image\":{\"@id\":\"https:\\\/\\\/machinelearningplus.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Collections - An Introductory Guide - machinelearningplus","description":"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/localhost:8080\/python-collections-guide\/","og_locale":"en_US","og_type":"article","og_title":"Python Collections - An Introductory Guide - machinelearningplus","og_description":"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.","og_url":"https:\/\/localhost:8080\/python-collections-guide\/","og_site_name":"machinelearningplus","article_modified_time":"2021-05-27T09:11:50+00:00","og_image":[{"width":1280,"height":720,"url":"https:\/\/localhost:8080\/wp-content\/uploads\/2020\/05\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"18 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/localhost:8080\/python-collections-guide\/","url":"https:\/\/localhost:8080\/python-collections-guide\/","name":"Python Collections - An Introductory Guide - machinelearningplus","isPartOf":{"@id":"https:\/\/machinelearningplus.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/localhost:8080\/python-collections-guide\/#primaryimage"},"image":{"@id":"https:\/\/localhost:8080\/python-collections-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2020\/05\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png","datePublished":"2020-05-17T05:08:04+00:00","dateModified":"2021-05-27T09:11:50+00:00","description":"Collections is a built-in python module that provides useful container types. They allow us to store and access values in a convenient way. Generally, you would have used lists, tuples, and dictionaries. But, while dealing with structured data we need smarter objects.","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/localhost:8080\/python-collections-guide\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/localhost:8080\/python-collections-guide\/#primaryimage","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2020\/05\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2020\/05\/Blue-Dynamic-Fitness-Youtube-Thumbnail-3-min.png","width":1280,"height":720},{"@type":"WebSite","@id":"https:\/\/machinelearningplus.com\/#website","url":"https:\/\/machinelearningplus.com\/","name":"machinelearningplus","description":"Learn Data Science (AI \/ ML) Online","publisher":{"@id":"https:\/\/machinelearningplus.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/machinelearningplus.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/machinelearningplus.com\/#organization","name":"machinelearningplus","url":"https:\/\/machinelearningplus.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/","url":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","contentUrl":"https:\/\/machinelearningplus.com\/wp-content\/uploads\/2022\/05\/MachineLearningplus-logo.svg","width":348,"height":36,"caption":"machinelearningplus"},"image":{"@id":"https:\/\/machinelearningplus.com\/#\/schema\/logo\/image\/"}}]}},"_links":{"self":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/pages\/3552","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/comments?post=3552"}],"version-history":[{"count":0,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/pages\/3552\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media\/3551"}],"wp:attachment":[{"href":"https:\/\/machinelearningplus.com\/wp-json\/wp\/v2\/media?parent=3552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}