OrderedDict, Defaultdict in Python Collections Module

A quick overview about ordereddict and defaultdict in the python collections module.

Photo by Terrence Thomas on Unsplash

Python Collections module:
Python collections module implements specialized container datatypes providing alternatives to python built in containers list,tuple,dict,set.

Let’s learn about OrderDict and defaultdict in collections module in this blog.

OrderedDict

From Python documentation:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict gained the ability to remember insertion order( (this new behavior became guaranteed in Python 3.7).

Syntax:

collections.OrderedDict([items])

Returns an instance of dict subclass,which contains methods for rearranging

Difference between OrderedDict and dict:

https://gist.github.com/IndhumathyChelliah/6653414c8ccc3c5ac8a0b33c33ad40c9

  1. Equality Operation in OrderedDict vs dict:

In OrderedDict, equality operation checks for matching order.It is order-sensitive.
But in dict, equality operation will check for matching (key,value) pairs.It is order-insensitive.
Equality operations between dict and OrderedDict is order-insensitive like regular dictionaries.

https://gist.github.com/IndhumathyChelliah/bbd38592e7b478708e59265aa9be1bc5

2. popitem() method in OrderedDict vs dict:

popitem(last=True)

In OrderedDict,popitem() returns and removes (key,value) pair. 
If last=True,the pairs are returned in LIFO(Last In First Out) order.Last inserted item will be removed and returned.
If last=False,the pairs are returned in FIFO(First In First Out)order.First inserted item will be removed and returned.

But in dict, popitem() will remove and return a (key, value) pair from the dictionary.Pairs are returned in LIFO order.

https://gist.github.com/IndhumathyChelliah/eb7655fa0118fe9880a4dbae24d80e27

3. move_to_end(key,last=True)

move_to_end() method in OrderedDict will move the existing key to either end of an ordered dictionary.
move_to_end(key,last=True)- Will move the item to the right end.
move_to_end(key,last=False)-will move the item to the beginning.

move_to_end() method is not supported in dict.

https://gist.github.com/IndhumathyChelliah/11affa56702c09fe117a7126ce556e56

4. reversed() in OrderedDict vs dict:

Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.
It is supported in OrderedDict from Python version 3.5
It is supported in dict from Python version 3.8.

https://gist.github.com/IndhumathyChelliah/9842687204900abc71e85388d24d0432

OrderedDict examples:

  1. We can create an ordered dictionary, which remembers the order in which keys are last inserted. If we update any existing keys,it will be moved to the end.

__setitem__() method is called to implement assignment of self[‘key’]

https://gist.github.com/IndhumathyChelliah/fed74df7823c761d402c1f6b5be96681


defaultdict

defautdict is a subclass of built-in dict class.Returns a new dict like object.
It overrides one method __missing__(key) and adds one writable instance variable default_factory.Remaining functionality same as dict class.

Refer to my story for dict operations.

collections.defaultdict(default_factory)

The first argument of defaultdict provides the initial value of default_factory attribute.It defaults to None.

default_factory

It is the function which returns the default value for the key which doesn’t exists in the dictionary.If default_factory is not specified,it raises KeyError.

Example 1: default_factory given as int

https://gist.github.com/IndhumathyChelliah/e34d5c1ce219893a89cc33324fbd259a

Example 2:default factory given as list.

https://gist.github.com/IndhumathyChelliah/63b9fc7566dfe98d889f3e5835e7916c

Example 3: default_factory given as lambda function.

https://gist.github.com/IndhumathyChelliah/0cb81d64110a0fa7c7e0e07e22c0464b

Example 4: default_factory is given as user_defined function.

https://gist.github.com/IndhumathyChelliah/c8287ad8a2f99225d2e76866efd54738

Example 5: If default_factory is not mentioned, and if we access the key which doesn’t exists in the defaultdict ,it raises KeyError.

https://gist.github.com/IndhumathyChelliah/fd5cb4905fd5f1b1558f65b74c2d1f59

In regular dictionary,if we access the key which doesn’t exists in the dictionary means,it raises KeyError.

https://gist.github.com/IndhumathyChelliah/7fcbe09ed41c1058ad8501a355f46b28

__missing__(key)

This function is used to specify the default value for the key in the dictionary.

  1. If the default_factory attribute is None, this raises a KeyError exception with the key as argument.

https://gist.github.com/IndhumathyChelliah/68240135148e0a11e01945ade6b9e51b

2. If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

https://gist.github.com/IndhumathyChelliah/938ae235bb0ab8994c10f05359aa370a

3.If calling default_factory raises an exception this exception is propagated unchanged.

https://gist.github.com/IndhumathyChelliah/c317d7c5df39e557f0e5c6e1e8f76ddd

4. This method is called by the __getitem__() method of the dict class when the requested key is not found,whatever it returns or raises is then returned or raised by__getitem__() .

__getitem__() is called to implement evaluation of self[key].

  • In defautdict:
    __getitem__(): If key exists return the value , else call __missing__() method.
  • In regular dict:
    __getitem__():If key exists return the value, else will raise KeyError.

https://gist.github.com/IndhumathyChelliah/0e4710cb3b3599fa22cadd846cea47e4

5. __missing__() method is not called for any other operations besides __getitem__().

get() method -> returns None if key doesn’t exists in the dictionary.It won’t use default_factory.

https://gist.github.com/IndhumathyChelliah/3a62135a8dbddf45a9d9efdea67c2b49

defaultdict Examples:

Example 1: Easy to group a sequence of (key,value) pairs to dictionary of lists.

When each key is encountered for first time, list.append() method will append its value to empty list.Since default_factory is mentioned as list. Its default value will be []empty list.
When keys are encountered again,list.append() will add another value to that list.

https://gist.github.com/IndhumathyChelliah/f9f41b05477085aad584ca22a3a890e6

Example 2:Converting letters in string as key and their frequency as values.

When a letter is first encountered,default_factory function calls int()to supply a default count of zero.The increment operation then builts up the count for each letter.
When letter is encountered again,increment operation will increment the count for that letter.

https://gist.github.com/IndhumathyChelliah/39de4cc037560c7297d76fd67d6d61e2

Conclusion:

move_to_end(key,last=False)-Return type is None. It will rearrange the original ordered dictionary itself.
reversed()-Return type is iterator object
popitem(last=True)-Return type is tuple.

Resources:

OrderedDict:

https://docs.python.org/3/library/collections.html#collections.OrderedDict

defaultdict:

https://docs.python.org/3/library/collections.html#collections.defaultdict

__setitem__()

https://docs.python.org/3/library/collections.html#collections.defaultdict

__getitem__()

https://docs.python.org/3/reference/datamodel.html#object.__getitem__

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s