A quick overview about ordereddict and defaultdict in the python collections module.
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.
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
dictgained the ability to remember insertion order( (this new behavior became guaranteed in Python 3.7).
Returns an instance of dict subclass,which contains methods for rearranging
Difference between OrderedDict and dict:
- Equality Operation in OrderedDict vs dict:
OrderedDict, equality operation checks for matching order.It is order-sensitive.
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.
2. popitem() method in OrderedDict vs dict:
In OrderedDict,popitem() returns and removes (key,value) pair.
last=True,the pairs are returned in
LIFO(Last In First Out) order.Last inserted item will be removed and returned.
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.
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.
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.
- 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
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.
The first argument of defaultdict provides the initial value of default_factory attribute.It defaults to None.
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
Example 2:default factory given as list.
Example 3: default_factory given as lambda function.
Example 4: default_factory is given as user_defined function.
Example 5: If default_factory is not mentioned, and if we access the key which doesn’t exists in the defaultdict ,it raises KeyError.
In regular dictionary,if we access the key which doesn’t exists in the dictionary means,it raises KeyError.
This function is used to specify the default value for the key in the dictionary.
- If the default_factory attribute is None, this raises a KeyError exception with the key as argument.
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.
3.If calling default_factory raises an exception this exception is propagated unchanged.
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__() is called to implement evaluation of self[key].
- In defautdict:
__getitem__(): If key exists return the value , else call
- In regular dict:
__getitem__():If key exists return the value, else will raise KeyError.
__missing__() method is not called for any other operations besides
get() method -> returns None if key doesn’t exists in the dictionary.It won’t use default_factory.
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.
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.
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.