Python Collections Module

devops everyday challenge
devops-challenge
Published in
2 min readApr 25, 2017

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

  • Counter: dict subclass for counting hashable objects
>>> from collections import Counter
>>> mylist = [1,2,3,4,5,1,3,2,4,5,2,3,4,1,2]
>>> Counter(mylist)
Counter({2: 4, 1: 3, 3: 3, 4: 3, 5: 2})

So as you can see it count the number of occurrences of each of these objects or elements in that list. so this is quick and easy way to count the number of element in the list and it act like a dictionary.

Same as with string,it count the number of iterables

>>> mystr = “mynasdbdadddndashhhqas”
>>> Counter(mystr)
Counter({‘d’: 6, ‘a’: 4, ‘s’: 3, ‘h’: 3, ’n’: 2, ‘m’: 1, ‘y’: 1, ‘b’: 1, ‘q’: 1})

One more example

>>> mysent = “Welcome to the world of Python Python is an awesome langauge”
>>> mysent = mysent.split()
>>> Counter(mysent)
Counter({‘Python’: 2, ‘Welcome’: 1, ‘to’: 1, ‘the’: 1, ‘world’: 1, ‘of’: 1, ‘is’: 1, ‘an’: 1, ‘awesome’: 1, ‘langauge’: 1})

Now look at methods of Counters

  • Let me show two most common words
>>> mysent = “Welcome to the world of Python Python is an awesome langauge to learn”
>>> mysent = mysent.split()
>>> x = Counter(mysent)
>>> x.most_common(2)
[(‘to’, 2), (‘Python’, 2)]
  • We can also perform sum of values
>>> sum(x.values())
13
  • defaultdict: dict subclass that calls a factory function to supply missing values

A defaultdict will never raise a KeyError. Any key that doesn’t exist gets the value returned by the default factory.

>>> from collections import defaultdict
>>> mydict = {}
>>> mydict[1]
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
KeyError: 1

Now let’s try to create the same dictionary using defaultdict, this time it doesn’t throw any error instead it return whatever the factory condition here for that value.

>>> mydict = defaultdict(object)
>>> mydict[1]
<object object at 0x101217110>

As you can see here, now we have key assigned to it

>>> for i in mydict:
… print(i)

1

So the key takeaway it’s doesn’t throw a key error instead it will initialize the default value that we placed when we created the default dictionary

  • OrderedDict: dict subclass that remembers the order entries were added(as dictionaries doesn’t retain order when created)
>>> d = {“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}>>> for k,v in d.items():
… print(k,v)

a 1
b 2
c 3
e 5 <-- as normal dictionaries are just the mapping,items are out of order
d 4

Now let’s do it using OrderedDict

>>> d = OrderedDict()>>> d = {“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}
>>> for k,v in d.items():
… print(k,v)

a 1
b 2
c 3
d 4
e 5

--

--