Defaultdict, OrderedDict from Collections module of Python

In this tutorial, you are going to learn about the defaultdict and OrderedDict of collections module. Collections module is an inbuilt module of Python. It’s a special datatypes container which provides an alternative to the inbuilt containers of Python’s i.e., dict, list, set and tuple.

defaultdict of collections module in Python

It returns a new dictionary like object which has all methods same as the dictionary, but it takes the first argument (default_factory) as the data type of the dictionary.
Syntax: defaultdict ([default_factory[,…]])
The default_factory has a default value which is none. It gives a key error if the key is not present in the dictionary.

# import the module
from collections import defaultdict
# Taking the default value(none)
dd=defaultdict()
# inserting the values in the dict
dd['a']=(1,2,3,3)
print(dd)
print(dd['b']) # gives an error as 'b' is not a key in the dict.

Output:-

defaultdict(None, {'a': (1, 2, 3, 3)})
print(dd['b'])
KeyError: 'b'

If the default_factory has its argument, then it becomes the data type of the dictionary. It does not raise a key error when we try to access the key which is not present in the dictionary. It returns the empty tuple, list, set or dict as mentioned in the argument of the defaultdict.

A program for the defaultdict taking tuple as the argument:

For ex: defaultdict(tuple)
then the datatype of {‘a’: (1, 2, 3, 3)} becomes the tuple.
For ex: dd[‘b’]
returns an empty tuple as the key is not present in the dictionary.

from collections import defaultdict
dd=defaultdict(tuple)
dd['a']=(1,2,3,3)
print(dd)
print(dd['b'])

Output:-

defaultdict(<class 'tuple'>, {'a': (1, 2, 3, 3)})
()

A program for the defaultdict taking set as the argument:




For ex: defaultdict (set)
returns the datatype of the dictionary, i.e., {‘a’ :{1, 2, 3}} as the set where the duplicate elements are eliminated.
For ex: dd[‘b’]
returns the empty set as the key is not present in the dictionary.

from collections import defaultdict
dd=defaultdict(set)
dd['a']={1,2,3,3,2}
print(dd)
print(dd['b'])

Output:-

defaultdict(<class 'set'>, {'a': {1, 2, 3}})
set()

A program for the defaultdict taking dict as the argument:

For ex: defaultdict (dict)
returns the datatype of the dictionary as the dict.
For ex: dd[‘b’]
returns an empty dictionary as the key is not present in the dictionary.

from collections import defaultdict
dd=defaultdict(dict)
dd['a']={'a':1,'bb':2,'b':3,'e':3,'bb':2}
print(dd)
print(dd['a'])
print(dd['b'])

Output:-

defaultdict(<class 'dict'>, {'a': {'a': 1, 'bb': 2, 'b': 3, 'e': 3}})
{'a': 1, 'bb': 2, 'b': 3, 'e': 3}
{}

OrderedDict of collections module in Python

Ordered dictionaries are just like the regular dictionaries, but they have some extra capabilities related to the ordering operations.

A program for sorting the dictionary:

d1={'a':100,'d':20,'c':"abc",'b':100}  #dict 1
d2={'a':10,'bc':200,'csd':60,'b':100}  #dict 2
#import the module
from collections import OrderedDict

od=OrderedDict(sorted(d1.items(),key=lambda t:t[0]))
print(od)
print(type(od))

od1=OrderedDict(sorted(d2.items(),key=lambda t:t[1]))
print(od1)

od2=OrderedDict(sorted(d2.items(),key=lambda t:len(t[0])))
print(od2)

Output:-

OrderedDict([('a', 100), ('b', 100), ('c', 'abc'), ('d', 20)])
<class 'collections.OrderedDict'>
OrderedDict([('a', 10), ('csd', 60), ('b', 100), ('bc', 200)])
OrderedDict([('a', 10), ('b', 100), ('bc', 200), ('csd', 60)])

A program using popitem and move_to_end built-in methods of OrderedDict:

popitem(last=True)  

This method will pop (or remove) an element from the dictionary. It will remove the last element if last is True else remove the first element as the last is False.

move_to_end(key, last=True)

This method will move the element from the beginning to the end of the dictionary if last is True else it will move the last element to the beginning of the dictionary as the last is False.

# import the module
from collections import OrderedDict
od3=OrderedDict.fromkeys('akmklslk')
print(od3)
# use of popitem()
q=od3.popitem(last=False)
print(q)
# use of move_to_end()
u=od3.move_to_end('k')
print(od3)

Output:-

OrderedDict([('a', None), ('k', None), ('m', None), ('l', None), ('s', None)])
('a', None)
OrderedDict([('m', None), ('l', None), ('s', None), ('k', None)])

Check out the other tutorials on Python:

Creation, Addition, Removal and Modification of Dictionary in Python

Python program to print numeric pattern


Leave a Reply

Your email address will not be published. Required fields are marked *