{"id":11257,"date":"2016-03-08T12:11:36","date_gmt":"2016-03-08T10:11:36","guid":{"rendered":"https:\/\/www.webcodegeeks.com\/?p=11257"},"modified":"2016-03-02T15:44:34","modified_gmt":"2016-03-02T13:44:34","slug":"python-collections-high-performing-containers-complex-problems","status":"publish","type":"post","link":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/","title":{"rendered":"Python Collections : High Performing Containers For Complex Problems"},"content":{"rendered":"<h2>1.Introduction<\/h2>\n<p>Python is known for its powerful\u00a0general purpose built-in data types like <em>list<\/em>, <em>dict<\/em>, <em>tuple<\/em> and <em>set<\/em>. \u00a0But Python also has collection objects like Java and C++. \u00a0These objects are developed on top of the general built-in containers with addtional functionalities which can be used in special scenarios.<\/p>\n<p>The objective of this article is to introduce\u00a0python collection objects and explain them with apropriate\u00a0code snippets. \u00a0The collections library contains the collections objects, they are namedtuples (v2.6), deque (v2.4), ChainMap(v3.3), Counter(v2.7 ), OrderedDict(v2.7), defaultdict(v2.5) . \u00a0Python 3.x also has userDict, userList, userString to create own custom container\u00a0types (not in the scope of this article), which deserves a separate article.<\/p>\n<p>NOTE: Python 2.x user might aware of various releases they are objects got introduced. \u00a0All these objects are available in Python 3.x from 3.1 onwards, except that ChainMap which \u00a0got introduced in v3.3. \u00a0All the code snippets in the articles are executed in Python 3.5 environment.<\/p>\n<h2>2. Namedtuple<\/h2>\n<p>As the name suggests, namedtuple is a tuple with name. \u00a0In standard tuple, we access the elements using the index, whereas namedtuple allows user to define name for elements. \u00a0This is very handy especially processing csv (comma separated value) files and working with complex and large dataset, where the code becomes messy with the use of indices (not so pythonic).<\/p>\n<h3>2.1\u00a0Example 1<\/h3>\n<p>Namedtuples are available in collections library in python. We have to import collections library before using any of container object from this library.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt;from collections import namedtuple\r\n&gt;&gt;&gt;saleRecord = namedtuple('saleRecord','shopId saleDate salesAmout totalCustomers')\r\n&gt;&gt;&gt;\r\n&gt;&gt;&gt;\r\n&gt;&gt;&gt;#Assign values to a named tuple \r\n&gt;&gt;&gt;shop11=saleRecord(11,'2015-01-01',2300,150) \r\n&gt;&gt;&gt;shop12=saleRecord(shopId=22,saleDate=\"2015-01-01\",saleAmout=1512,totalCustomers=125)<\/pre>\n<p>In the above code snippet, in the first line we import namedtuple from the collections library. In the second line we create a namedtuple called \u201csaleRecord\u201d, which has\u00a0shopId, saleDate, salesAmount and totalCustomers as fields. Note\u00a0that namedtuple() takes two string arguments, first argument is the name of tuple and second argument is the list of fields names seperated by <strong>space<\/strong> or <strong>comma<\/strong>. In the above example\u00a0space is used as delimeter.<br \/>\nWe have also created two tuples here. They are shop11 and shop12. \u00a0For shop11, the\u00a0values are assigned to fields based on the order of the fields and shop12, the values are\u00a0assigned using the names.<\/p>\n<h3>2.2\u00a0Example 2<\/h3>\n<pre class=\"brush:python\">&gt;&gt;&gt;#Reading as a namedtuple\r\n&gt;&gt;&gt;print(\"Shop Id =\",shop12.shopId)\r\n12\r\n&gt;&gt;&gt;print(\"Sale Date=\",shop12.saleDate)\r\n2015-01-01\r\n&gt;&gt;&gt;print(\"Sales Amount =\",shop12.salesAmount)\r\n1512\r\n&gt;&gt;&gt;print(\"Total Customers =\",shop12.totalCustomers)\r\n125<\/pre>\n<p>The above code is pretty much clear that tuple is accessed using the names. It is also possible to access them using indexes of the tuples which is the usual way.<\/p>\n<h3>2.3 Interesting Methods and Members<\/h3>\n<h4>2.3.1\u00a0_make<\/h4>\n<p>The _make method is used to convert the given iteratable item (list, tuple,dictionary) into a named tuple.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt;#Convert a list into a namedtuple\r\n&gt;&gt;&gt;aList = [101,\"2015-01-02\",1250,199]\r\n&gt;&gt;&gt;shop101 = saleRecord._make(aList)\r\n&gt;&gt;&gt;print(shop101)\r\nsaleRecord(shopId=101, saleDate='2015-01-02', salesAmount=1250, totalCustomers=199)\r\n\r\n&gt;&gt;&gt;#Convert a tuple into a namedtuple\r\n&gt;&gt;&gt;aTup =(108,\"2015-02-28\",1990,189)\r\n&gt;&gt;&gt;shop108=saleRecord._make(aTup)\r\n&gt;&gt;&gt;print(shop108)\r\nsaleRecord(shopId=108, saleDate='2015-02-28', salesAmount=1990, totalCustomers=189)\r\n&gt;&gt;&gt;<\/pre>\n<h4>2.3.2 _fields<\/h4>\n<p>The _fields is a tuple, which contains the names of the tuple.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt;print(sho108._fields)\r\n&gt;&gt;&gt;('shopId', 'saleDate', 'salesAmount', 'totalCustomers')<\/pre>\n<h3>2.4 CSV File Processing<\/h3>\n<p>As we discussed namedtuple will be very handy while processing a csv data file, where we can access the data using names instead of indexes, which make the code more meaningful and efficient.<\/p>\n<pre class=\"brush:python\">from csv import reader\r\nfrom collections import namedtuple\r\n\r\nsaleRecord = namedtuple('saleRecord','shopId saleDate totalSales totalCustomers')\r\nfileHandle = open(\"salesRecord.csv\",\"r\")\r\ncsvFieldsList=csv.reader(fileHandle)\r\nfor fieldsList in csvFieldsList:\r\n    shopRec = saleRecord._make(fieldsList)\r\n    overAllSales += shopRec.totalSales;\r\n\r\nprint(\"Total Sales of The Retail Chain =\",overAllSales)<\/pre>\n<p>In the above code snippet, we have the files salesRecord.csv which contains sales records of shops of a particular retain chain. It contains the values for the fields shopId,saleDate,totalSales,totalCustomers. The fields are delimited by comma and the records are delimited by new line.<br \/>\nThe csv.reader() read the file and provides a iterator. The iterator, \u201ccsvFieldsList\u201d provides list of fields for every single row of the csv file. As we know the _make() converts the list into namedtuple and the rest of the code is self explanatory.<\/p>\n<h2>3.Counter<\/h2>\n<p>Counter is used for rapid tallies. \u00a0It is a dictionary, where the elements are stored as keys and their counts are stored as values.<\/p>\n<h3>3.1 Creating Counters<\/h3>\n<p>The Counter() class takes an iteratable object as an argument and computes the count for each element in the object and present as a key value pair.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt;from collections import Counter\r\n&gt;&gt;&gt;listOfInts=[1,2,3,4,1,2,3,1,2,1]\r\n&gt;&gt;&gt;cnt=Counter(listOfInts)\r\n&gt;&gt;&gt;print(cnt)\r\nCounter({1: 4, 2: 3, 3: 2, 4: 1})<\/pre>\n<p>In the above code snippet, <em>listOfInts<\/em> is a list which contains numbers. It is passed to <em>Counter()<\/em> and we got cnt, which is a container object. The <em>cnt<\/em> is a dictionary, which contains the unique numbers present in the given list as keys, and their respect counts as the value.<\/p>\n<h3>3.2 Accessing Counters<\/h3>\n<p>Counter is a subclass of dictionary. \u00a0So it can be accessed the same as dictionary. \u00a0 The \u201ccnt\u201d can be handled as a regular dictionary object.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; cnt.items()\r\ndict_items([(1, 4), (2, 3), (3, 2), (4, 1)])\r\n&gt;&gt;&gt; cnt.keys()\r\ndict_keys([1, 2, 3, 4])\r\n&gt;&gt;&gt; cnt.values()\r\ndict_values([4, 3, 2, 1])<\/pre>\n<h3>3.3 Interesting Methods &amp; Usecases<\/h3>\n<h4>3.3.1 most_common<\/h4>\n<p>The <em>most_common(n)<\/em> of Counter class, provides most commonly occured keys. The <em>n<\/em> is used as a rank, for example, <em>n = 2<\/em> will provide top two keys.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt;name = \"Saravanan Subramanian\"\r\n&gt;&gt;&gt;letterCnt=Counter(name)\r\n&gt;&gt;&gt;letterCnt.most_common(1)\r\n[('a', 7)]\r\n&gt;&gt;&gt;letterCnt.most_common(2)\r\n[('a', 7), ('n', 4)]\r\n&gt;&gt;&gt;letterCnt.most_common(3)\r\n[('a', 7), ('n', 4), ('r', 2)]<\/pre>\n<p>In the above code, we could see that the string is parsed as independent characters as keys and their respective count is\u00a0stored as values. So, the letterCnt.most_common(1) provides the top letter which has highest occurances.<\/p>\n<h4>3.3.2 Operations on Counter<\/h4>\n<p>The Counter() subclass is also called as Multiset. It supports addition, substraction, unition and intersection operations on the Counter class.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; a = Counter(x=1,y=2,z=3)\r\n&gt;&gt;&gt; b = Counter(x=2,y=3,z=4)\r\n&gt;&gt;&gt; a+b\r\nCounter({'z': 7, 'y': 5, 'x': 3})\r\n&gt;&gt;&gt; a-b       #This will result in negative values &amp; will be omitted\r\nCounter()    \r\n&gt;&gt;&gt; b-a\r\nCounter({'y': 1, 'x': 1, 'z': 1})\r\n&gt;&gt;&gt; a &amp; b    #Chooses the minimum values from their respective pair\r\nCounter({'z': 3, 'y': 2, 'x': 1})\r\n&gt;&gt;&gt; a | b   #Chooses the maximum values from their respective pair\r\nCounter({'z': 4, 'y': 3, 'x': 2})<\/pre>\n<h2>4. Default Dictionary<\/h2>\n<p>The defaultdict() is available part of collections library. It allows the user to specify a function to be called when key is not present in the dictionary.<\/p>\n<p>In a standard dictionary, accesing an element where the key is not present, will raise \u201cKey Error\u201d. So, this is a problem when working working with collections (list, set, etc), especially while creating them.<\/p>\n<p>So, when a dictionary is queried for a key, which is not exists, the function passed as an argument to the named argument \u201cdefault_dictionary\u201d of default_dict() will called to set a value for given \u201ckey\u201d into dictionary.<\/p>\n<h3>4.1 Creating Default Dictionary<\/h3>\n<p>The defaultdict() is available part of collections library. \u00a0The default dict takes a function without argument which returns value as an argument.<\/p>\n<h4>4.1.1 Example 1<\/h4>\n<pre class=\"brush:python\">&gt;&gt;&gt; \r\n&gt;&gt;&gt; booksIndex = defaultdict(lambda:'Not Available')\r\n&gt;&gt;&gt; booksIndex['a']='Arts'\r\n&gt;&gt;&gt; booksIndex['b']='Biography'\r\n&gt;&gt;&gt; booksIndex['c']='Computer'\r\n&gt;&gt;&gt; print(booksIndex)\r\ndefaultdict(&lt;function  at 0x030EB3D8&gt;, {'c': 'Computer', 'b': 'Biography', 'a': 'Arts'})\r\n&gt;&gt;&gt; booksIndex['z']\r\n'Not Available'\r\n&gt;&gt;&gt; print(booksIndex)\r\ndefaultdict(&lt;function  at 0x030EB3D8&gt;, {'c': 'Computer', 'b': 'Biography', 'z': 'Not Available', 'a': 'Arts'})\r\n&gt;&gt;&gt;<\/pre>\n<p>In the above example, the <em>booksIndex<\/em> is a defaultdict, where it set \u2018<em>Not Available<\/em>\u201d as a value if any non-existant key is accessed. We have added values for keys a, b &amp; c into the <em>defaultdict<\/em>. The <em>print(booksIndex)<\/em> shows that the <em>defaultdict<\/em> contains values only for these keys. While trying to access the value for key \u2018z\u2019, which we have not set, it returned value as \u2018<em>Not Available<\/em>\u2018 and updated the dictionary.<\/p>\n<h4>4.1.2 Example 2<\/h4>\n<pre class=\"brush:python\">&gt;&gt;&gt; titleIndex = [('a','Arts'),('b','Biography'),('c','Computer'),('a','Army'),('c','Chemistry'),('d','Dogs')]\r\n&gt;&gt;&gt; rackIndices = defaultdict(list)\r\n&gt;&gt;&gt; for id,title in titleIndex:\r\n\trackIndices[id].append(title)\t\r\n&gt;&gt;&gt; rackIndices.items()\r\ndict_items([('d', ['Dogs']), ('b', ['Biography']), ('a', ['Arts', 'Army']), ('c', ['Computer', 'Chemistry'])])\r\n&gt;&gt;&gt;<\/pre>\n<p>In the above example, <em>titleIndex<\/em> contains a list of tuples. We want to aggregate this list of tuples to identify titles for each alphabets. So, we can have a dictionary where key is the alphabet and value is the list of titles. Here we used a defaultdict with \u201clist\u201d as a function to be called for missing elements. So for each new elements list will be called, and it will create an empty list object. The consecutive <em>append()<\/em> methods on the list will add elements to the list.<\/p>\n<h2>5. Ordered Dictionary<\/h2>\n<p>The ordered dictionary maintains\u00a0the order of elements addition into the dictionary, where the standard dictionary will not maintain the order of inclusion.<\/p>\n<h3>5.1 Ordered Dictionary Creation<\/h3>\n<p>Ordered Dictionary is created using <em>OrderedDict()<\/em> from collections library. It an subsclass of regular dictionary, so it inherits all other methods and behaviours of regular dictionary.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; from collections import OrderedDict\r\n&gt;&gt;&gt; dOrder=OrderedDict()\r\n&gt;&gt;&gt; dOrder['a']='Alpha'\r\n&gt;&gt;&gt; dOrder['b']='Bravo'\r\n&gt;&gt;&gt; dOrder['c']='Charlie'\r\n&gt;&gt;&gt; dOrder['d']='Delta'\r\n&gt;&gt;&gt; dOrder['e']='Echo'\r\n&gt;&gt;&gt; dOrder\r\n&gt;&gt;&gt; OrderedDict([('a', 'Alpha'), ('b', 'Bravo'), ('c', 'Charlie'), ('d', 'Delta'), ('e', 'Echo')])\r\n&gt;&gt;&gt; &gt;&gt;&gt; dOrder.keys()\r\nodict_keys(['a', 'b', 'c', 'd', 'e'])\r\n&gt;&gt;&gt; dOrder.values()\r\nodict_values(['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo'])\r\n&gt;&gt;&gt; dOrder.items()\r\nodict_items([('a', 'Alpha'), ('b', 'Bravo'), ('c', 'Charlie'), ('d', 'Delta'), ('e', 'Echo')])\r\n&gt;&gt;&gt;<\/pre>\n<h3>5.2 Creating from other iteratable items<\/h3>\n<p>OrderedDict can also be created by passing an dictionary or a list of key, value pair tuples.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; from collections import OrderedDict\r\n&gt;&gt;&gt; listKeyVals = [(1,\"One\"),(2,\"Two\"),(3,\"Three\"),(4,\"Four\"),(5,\"Five\")]\r\n&gt;&gt;&gt; x = OrderedDict(listKeyVals)\r\n&gt;&gt;&gt; x\r\nOrderedDict([(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five')])\r\n&gt;&gt;&gt;<\/pre>\n<h3>5.3 Sort and Store<\/h3>\n<p>One of the interesting use case for OrderedDict is Rank problem. For example, consider the problem a dictionary contains students names and their marks, now we have to find out the best student and rank them according to their marks. So, OrderedDict is the right choice here. Since OrderedDict will remember the order or addition and sorted() will sort a dictionary we can combine both to created a rank list based on the student marks. Please check the example below:<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; studentMarks={}\r\n&gt;&gt;&gt; studentMarks[\"Saravanan\"]=100\r\n&gt;&gt;&gt; studentMarks[\"Subhash\"]=99\r\n&gt;&gt;&gt; studentMarks[\"Raju\"]=78\r\n&gt;&gt;&gt; studentMarks[\"Arun\"]=85\r\n&gt;&gt;&gt; studentMarks[\"Hasan\"]=67\r\n&gt;&gt;&gt; studentMarks\r\n{'Arun': 85, 'Subhash': 99, 'Raju': 78, 'Hasan': 67, 'Saravanan': 100}\r\n&gt;&gt;&gt; sorted(studentMarks.items(),key=lambda t:t[0])\r\n[('Arun', 85), ('Hasan', 67), ('Raju', 78), ('Saravanan', 100), ('Subhash', 99)]\r\n&gt;&gt;&gt; sorted(studentMarks.items(),key=lambda t:t[1])\r\n[('Hasan', 67), ('Raju', 78), ('Arun', 85), ('Subhash', 99), ('Saravanan', 100)]\r\n&gt;&gt;&gt; sorted(studentMarks.items(), key = lambda t:-t[1])\r\n[('Saravanan', 100), ('Subhash', 99), ('Arun', 85), ('Raju', 78), ('Hasan', 67)]\r\n&gt;&gt;&gt; rankOrder = OrderedDict(sorted(studentMarks.items(), key = lambda t:-t[1]))\r\n&gt;&gt;&gt; rankOrder\r\nOrderedDict([('Saravanan', 100), ('Subhash', 99), ('Arun', 85), ('Raju', 78), ('Hasan', 67)])<\/pre>\n<p>In the above example, <i>studentMarks<\/i> is a dictionary contains the student name as a key and their mark as the value. It got sorted using its value and passed to OrderedDict and got stored in <i>rankOrder<\/i>. Now <i>rankOrder<\/i> contains the highest marked student as the first entry, and next highest as the second entry and so on. This ordered is presevered in this dictionary.<\/p>\n<h2>6. Deque<\/h2>\n<p>Deque means double ended queue and it pronounced as \u201cdeck\u201d. It is an extention to the standard list data structure. The standard list allows the user to append or extend elements only at the end. But deque allows the user to operate on both ends, so that the user can implement both stacks and queues.<\/p>\n<h3>6.1 Creation &amp; Performing Operations on Deque<\/h3>\n<p>The deque() is available in collections library. It takes iteratable entity as an argument and an optional maximum length. If <em>maxlen<\/em> is set, it ensure that deque length does not exceeds the size of the <em>maxlen<\/em>.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; from collections import deque\r\n&gt;&gt;&gt; aiao = deque([1,2,3,4,5],maxlen=5)\r\naiao = deque([1,2,3,4,5])\r\n&gt;&gt;&gt; aiao.append(6)\r\n&gt;&gt;&gt; aiao\r\ndeque([2, 3, 4, 5, 6], maxlen=5)\r\n&gt;&gt;&gt; aiao.appendleft(1)\r\n&gt;&gt;&gt; aiao\r\ndeque([1, 2, 3, 4, 5], maxlen=5)<\/pre>\n<p>In the above example, we have created a deque with maxlen 5, once we appended 6th element on the right, it pushed first element on the left. \u00a0Similarly, it pushes out the last element on the right when we append element on the left.<\/p>\n<h3>6.2\u00a0Operations on Right<\/h3>\n<p>Operations on the right are common to performing any opertions on the list. \u00a0The methods append(), extend() and pop() are operate on the rightside of the deque().<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; aiao.append(6)\r\n&gt;&gt;&gt; aiao\r\ndeque([2, 3, 4, 5, 6], maxlen=5)\r\n&gt;&gt;&gt; aiao.extend([7,8,9])\r\n&gt;&gt;&gt; aiao\r\ndeque([5, 6, 7, 8, 9], maxlen=5)\r\n&gt;&gt;&gt; aiao.pop()\r\n9<\/pre>\n<h3>6.3 Operation\u00a0on the Left<\/h3>\n<p>The special feature of performing operations on the left is supported by set of methods like appendleft(), extendleft(), popleft().<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; aiao = deque([1,2,3,4,5],maxlen=5)\r\n&gt;&gt;&gt; aiao.appendleft(0)\r\n&gt;&gt;&gt; aiao\r\ndeque([0, 1, 2, 3, 4], maxlen=5)\r\n&gt;&gt;&gt; aiao.extendleft([-1,-2,-3])\r\n&gt;&gt;&gt; aiao\r\ndeque([-3, -2, -1, 0, 1], maxlen=5)\r\n&gt;&gt;&gt; aiao.popleft()\r\n-3<\/pre>\n<h2>6.4\u00a0Example 2 (without maxlen)<\/h2>\n<p>If the maxlen value is not set, the deque does not perform any trimming operations to maintain the size of the deque.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; aiao = deque([1,2,3,4,5])\r\n&gt;&gt;&gt; aiao.appendleft(0)\r\n&gt;&gt;&gt; aiao\r\ndeque([0, 1, 2, 3, 4, 5])\r\n&gt;&gt;&gt; aiao.extendleft([-1,-2,-3])\r\n&gt;&gt;&gt; aiao\r\ndeque([-3, -2, -1, 0, 1, 2, 3, 4, 5])\r\n&gt;&gt;&gt;<\/pre>\n<p>From the above example, the deque <em>aiao<\/em> continues to grow for the append and extend operations performed on it.<\/p>\n<h2>7. ChainMap<\/h2>\n<p>ChainMap allows to combine multiple\u00a0dictionaries into a single dictionary, so that operations can be performed on single logical entity. \u00a0The ChainMap() does not create any new dictionary, instead it maintains references to the original dictionaries, all operations are performed only on the referred dictionaries.<\/p>\n<h3>7.1 Creating ChainMap<\/h3>\n<pre class=\"brush:python\">&gt;&gt;&gt; from collections import ChainMap\r\n&gt;&gt;&gt; x = {'a':'Alpha','b':'Beta','c':'Cat'}\r\n&gt;&gt;&gt; y = { 'c': \"Charlie\", 'd':\"Delta\", 'e':\"Echo\"}\r\n&gt;&gt;&gt; z = ChainMap(x,y)\r\n&gt;&gt;&gt; z\r\nChainMap({'c': 'Cat', 'b': 'Beta', 'a': 'Alpha'}, {'d': 'Delta', 'c': 'Charlie', 'e': 'Echo'})\r\n&gt;&gt;&gt; list(z.keys())\r\n['b', 'd', 'c', 'e', 'a']\r\n&gt;&gt;&gt; list(z.values())\r\n['Beta', 'Delta', 'Cat', 'Echo', 'Alpha']\r\n&gt;&gt;&gt; list(z.items())\r\n[('b', 'Beta'), ('d', 'Delta'), ('c', 'Cat'), ('e', 'Echo'), ('a', 'Alpha')]<\/pre>\n<p>We have created ChainMap z from other dictionaries x &amp; y. The ChainMap z is reference to the dictionaries x and y. ChainMap will not maintain duplicate keys, it returns presents value \u2018Cat\u2019 for key \u2018c\u2019. So, basically it skips the second occurance of the same key.<\/p>\n<pre class=\"brush:python\">&gt;&gt;&gt; x\r\n{'c': 'Cat', 'b': 'Beta', 'a': 'Alpha'}\r\n&gt;&gt;&gt; y\r\n{'d': 'Delta', 'c': 'Charlie', 'e': 'Echo'}\r\n&gt;&gt;&gt; x.pop('c')\r\n'Cat'\r\n&gt;&gt;&gt; x\r\n{'b': 'Beta', 'a': 'Alpha'}\r\n&gt;&gt;&gt; list(z.keys())\r\n['d', 'c', 'b', 'e', 'a']\r\n&gt;&gt;&gt; list(z.values())\r\n['Delta', 'Charlie', 'Beta', 'Echo', 'Alpha']\r\n&gt;&gt;&gt; list(z.items())\r\n[('d', 'Delta'), ('c', 'Charlie'), ('b', 'Beta'), ('e', 'Echo'), ('a', 'Alpha')]\r\n&gt;&gt;&gt;<\/pre>\n<p>In the above code, we have removed the key \u2018c\u2019 from dict x. Now the ChainMap points the value for key \u2018c\u2019 to \u201cCharlie\u201d, which is present in<em> y<\/em>.<\/p>\n<h2>8. Summary<\/h2>\n<p>We have seen various python collection data types and understand them with example and use cases. The official python documentation can be referred for further reading.<\/p>\n<h2>9. References<\/h2>\n<p>[1] \u2013 Python Wiki \u2013 <a href=\"https:\/\/docs.python.org\/3.5\/library\/collections.html\" rel=\"nofollow\">https:\/\/docs.python.org\/3.5\/library\/collections.html<\/a><\/p>\n<div class=\"attribution\">\n<table>\n<tbody>\n<tr>\n<td><span class=\"reference\">Reference: <\/span><\/td>\n<td><a href=\"http:\/\/techietweak.wordpress.com\/2015\/11\/11\/python-collections\/\">Python Collections : High Performing Containers For Complex Problems<\/a> from our <a href=\"http:\/\/www.webcodegeeks.com\/join-us\/wcg\/\">WCG partner<\/a> Saravanan Subramanian at the <a href=\"http:\/\/techietweak.wordpress.com\/\">Saravanan Subramanian Tech Notes<\/a> blog.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection objects like Java and C++. \u00a0These objects are developed on top of the general built-in containers with addtional functionalities which can be used in special scenarios. The objective of this article is to &hellip;<\/p>\n","protected":false},"author":143,"featured_media":1651,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[],"class_list":["post-11257","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\" \/>\n<meta property=\"og:site_name\" content=\"Web Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webcodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/saravanan.subramanian.31\" \/>\n<meta property=\"article:published_time\" content=\"2016-03-08T10:11:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Saravanan Subramanian\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@tosarvan\" \/>\n<meta name=\"twitter:site\" content=\"@webcodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Saravanan Subramanian\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\"},\"author\":{\"name\":\"Saravanan Subramanian\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/56779276fba995e603f50ea6f18bdd8a\"},\"headline\":\"Python Collections : High Performing Containers For Complex Problems\",\"datePublished\":\"2016-03-08T10:11:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\"},\"wordCount\":1712,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\",\"name\":\"Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"datePublished\":\"2016-03-08T10:11:36+00:00\",\"description\":\"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection\",\"breadcrumb\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.webcodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/www.webcodegeeks.com\/category\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python Collections : High Performing Containers For Complex Problems\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#website\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"name\":\"Web Code Geeks\",\"description\":\"Web Developers Resource Center\",\"publisher\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webcodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/www.webcodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webcodegeeks\",\"https:\/\/x.com\/webcodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/56779276fba995e603f50ea6f18bdd8a\",\"name\":\"Saravanan Subramanian\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/d5b5095370698b8a3f2dfd7ade5444c1b7ec66ed3f549b8a9dcda5580c3a80dd?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/d5b5095370698b8a3f2dfd7ade5444c1b7ec66ed3f549b8a9dcda5580c3a80dd?s=96&d=mm&r=g\",\"caption\":\"Saravanan Subramanian\"},\"description\":\"Saravanan Subramanian is a System Architect cum Agile Product Owner for developing cloud based applications for service provider back office enterprise applications using open source technologies. He is passionate about Cloud Technology and Big Data Analytics.\",\"sameAs\":[\"http:\/\/techietweak.wordpress.com\/\",\"https:\/\/www.facebook.com\/saravanan.subramanian.31\",\"https:\/\/in.linkedin.com\/in\/tosarvan\",\"https:\/\/x.com\/tosarvan\"],\"url\":\"https:\/\/www.webcodegeeks.com\/author\/saravanan-subramanian\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026","description":"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection","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:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/","og_locale":"en_US","og_type":"article","og_title":"Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026","og_description":"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection","og_url":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/","og_site_name":"Web Code Geeks","article_publisher":"https:\/\/www.facebook.com\/webcodegeeks","article_author":"https:\/\/www.facebook.com\/saravanan.subramanian.31","article_published_time":"2016-03-08T10:11:36+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","type":"image\/jpeg"}],"author":"Saravanan Subramanian","twitter_card":"summary_large_image","twitter_creator":"@tosarvan","twitter_site":"@webcodegeeks","twitter_misc":{"Written by":"Saravanan Subramanian","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#article","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/"},"author":{"name":"Saravanan Subramanian","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/56779276fba995e603f50ea6f18bdd8a"},"headline":"Python Collections : High Performing Containers For Complex Problems","datePublished":"2016-03-08T10:11:36+00:00","mainEntityOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/"},"wordCount":1712,"commentCount":0,"publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/","url":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/","name":"Python Collections : High Performing Containers For Complex Problems - Web Code Geeks - 2026","isPartOf":{"@id":"https:\/\/www.webcodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage"},"image":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage"},"thumbnailUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","datePublished":"2016-03-08T10:11:36+00:00","description":"1.Introduction Python is known for its powerful\u00a0general purpose built-in data types like list, dict, tuple and set. \u00a0But Python also has collection","breadcrumb":{"@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#primaryimage","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2014\/11\/python-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.webcodegeeks.com\/python\/python-collections-high-performing-containers-complex-problems\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.webcodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/www.webcodegeeks.com\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Collections : High Performing Containers For Complex Problems"}]},{"@type":"WebSite","@id":"https:\/\/www.webcodegeeks.com\/#website","url":"https:\/\/www.webcodegeeks.com\/","name":"Web Code Geeks","description":"Web Developers Resource Center","publisher":{"@id":"https:\/\/www.webcodegeeks.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webcodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webcodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.webcodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.webcodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webcodegeeks","https:\/\/x.com\/webcodegeeks"]},{"@type":"Person","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/56779276fba995e603f50ea6f18bdd8a","name":"Saravanan Subramanian","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webcodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/d5b5095370698b8a3f2dfd7ade5444c1b7ec66ed3f549b8a9dcda5580c3a80dd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d5b5095370698b8a3f2dfd7ade5444c1b7ec66ed3f549b8a9dcda5580c3a80dd?s=96&d=mm&r=g","caption":"Saravanan Subramanian"},"description":"Saravanan Subramanian is a System Architect cum Agile Product Owner for developing cloud based applications for service provider back office enterprise applications using open source technologies. He is passionate about Cloud Technology and Big Data Analytics.","sameAs":["http:\/\/techietweak.wordpress.com\/","https:\/\/www.facebook.com\/saravanan.subramanian.31","https:\/\/in.linkedin.com\/in\/tosarvan","https:\/\/x.com\/tosarvan"],"url":"https:\/\/www.webcodegeeks.com\/author\/saravanan-subramanian\/"}]}},"_links":{"self":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/11257","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/users\/143"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/comments?post=11257"}],"version-history":[{"count":0,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/posts\/11257\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media\/1651"}],"wp:attachment":[{"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/media?parent=11257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/categories?post=11257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webcodegeeks.com\/wp-json\/wp\/v2\/tags?post=11257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}