default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised.
DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument.
ChainMap
A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.
Syntax:
class collections.ChainMap(dict1, dict2)
Example:
Python3
from collections import ChainMap
d1 = { 'a' : 1 , 'b' : 2 }
d2 = { 'c' : 3 , 'd' : 4 }
d3 = { 'e' : 5 , 'f' : 6 }
c = ChainMap(d1, d2, d3)
print (c)
|
Output:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
Accessing Keys and Values from ChainMap
Values from ChainMap can be accessed using the key name. They can also be accessed by using the keys() and values() method.
Example:
Python3
from collections import ChainMap
d1 = { 'a' : 1 , 'b' : 2 }
d2 = { 'c' : 3 , 'd' : 4 }
d3 = { 'e' : 5 , 'f' : 6 }
c = ChainMap(d1, d2, d3)
print (c[ 'a' ])
print (c.values())
print (c.keys())
|
Output:
1
ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
Adding new dictionary
A new dictionary can be added by using the new_child() method. The newly added dictionary is added at the beginning of the ChainMap.
Example:
Python3
import collections
dic1 = { 'a' : 1 , 'b' : 2 }
dic2 = { 'b' : 3 , 'c' : 4 }
dic3 = { 'f' : 5 }
chain = collections.ChainMap(dic1, dic2)
print ( "All the ChainMap contents are : " )
print (chain)
chain1 = chain.new_child(dic3)
print ( "Displaying new ChainMap : " )
print (chain1)
|
Output:
All the ChainMap contents are :
ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Displaying new ChainMap :
ChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Note: For more information, refer ChainMap in Python
NamedTuple
A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.
Syntax:
class collections.namedtuple(typename, field_names)
Example:
Python3
from collections import namedtuple
Student = namedtuple( 'Student' ,[ 'name' , 'age' , 'DOB' ])
S = Student( 'Nandini' , '19' , '2541997' )
print ( "The Student age using index is : " ,end = "")
print (S[ 1 ])
print ( "The Student name using keyname is : " ,end = "")
print (S.name)
|
Output:
The Student age using index is : 19
The Student name using keyname is : Nandini
Conversion Operations
1. _make(): This function is used to return a namedtuple() from the iterable passed as argument.
2. _asdict(): This function returns the OrderedDict() as constructed from the mapped values of namedtuple().
Example:
Python3
from collections import namedtuple
Student = namedtuple( 'Student' ,[ 'name' , 'age' , 'DOB' ])
S = Student( 'Nandini' , '19' , '2541997' )
li = [ 'Manjeet' , '19' , '411997' ]
di = { 'name' : "Nikhil" , 'age' : 19 , 'DOB' : '1391997' }
print ( "The namedtuple instance using iterable is : " )
print (Student._make(li))
print ( "The OrderedDict instance using namedtuple is : " )
print (S._asdict())
|
Output:
The namedtuple instance using iterable is :
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
Note: For more information, refer NamedTuple in Python
Deque
Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.
Syntax:
class collections.deque(list)
This function takes the list as an argument.
Example:
Python3
from collections import deque
queue = deque([ 'name' , 'age' , 'DOB' ])
print (queue)
|
Output:
deque(['name', 'age', 'DOB'])
Inserting Elements
Elements in deque can be inserted from both ends. To insert the elements from right append() method is used and to insert the elements from the left appendleft() method is used.
Example:
Python3
from collections import deque
de = deque([ 1 , 2 , 3 ])
de.append( 4 )
print ( "The deque after appending at right is : " )
print (de)
de.appendleft( 6 )
print ( "The deque after appending at left is : " )
print (de)
|
Output:
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
Removing Elements
Elements can also be removed from the deque from both the ends. To remove elements from right use pop() method and to remove elements from the left use popleft() method.
Example:
Python3
from collections import deque
de = deque([ 6 , 1 , 2 , 3 , 4 ])
de.pop()
print ( "The deque after deleting from right is : " )
print (de)
de.popleft()
print ( "The deque after deleting from left is : " )
print (de)
|
Output:
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
Note: For more information, refer Deque in Python.
UserDict
UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality.
Syntax:
class collections.UserDict([initialdata])
Example:
Python3
from collections import UserDict
class MyDict(UserDict):
def __del__( self ):
raise RuntimeError( "Deletion not allowed" )
def pop( self , s = None ):
raise RuntimeError( "Deletion not allowed" )
def popitem( self , s = None ):
raise RuntimeError( "Deletion not allowed" )
d = MyDict({ 'a' : 1 ,
'b' : 2 ,
'c' : 3 })
d.pop( 1 )
|
Output:
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 32, in <module>
d.pop(1)
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 20, in pop
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: <bound method MyDict.__del__ of {'a': 1, 'b': 2, 'c': 3}>
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 15, in __del__
RuntimeError: Deletion not allowed
Note: For more information, refer UserDict in Python
UserList
UserList is a list like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality.
Syntax:
class collections.UserList([list])
Example:
Python3
from collections import UserList
class MyList(UserList):
def remove( self , s = None ):
raise RuntimeError( "Deletion not allowed" )
def pop( self , s = None ):
raise RuntimeError( "Deletion not allowed" )
L = MyList([ 1 , 2 , 3 , 4 ])
print ( "Original List" )
L.append( 5 )
print ( "After Insertion" )
print (L)
L.remove()
|
Output:
Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in <module>
L.remove()
File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Note: For more information, refer UserList in Python
UserString
UserString is a string like container and just like UserDict and UserList it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality.
Syntax:
class collections.UserString(seq)
Example:
Python3
from collections import UserString
class Mystring(UserString):
def append( self , s):
self .data + = s
def remove( self , s):
self .data = self .data.replace(s, "")
s1 = Mystring( "Geeks" )
print ( "Original String:" , s1.data)
s1.append( "s" )
print ( "String After Appending:" , s1.data)
s1.remove( "e" )
print ( "String after Removing:" , s1.data)
|
Output:
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
Note: For more information, refer UserString in Python
Last Updated :
08 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...