defaultdict() function in python by R4R Team

- The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet).The defaultdict is also a dictionary-like object and provides all methods provided by a dictionary.

Syntax-

collections.defaultdict()

Without defaultdict-

program-

x=dict()
print(x['a'])


output-

x=dict()

TypeError: 'Counter' object is not callable


-In this program, we create a dictionary and try to find the key value direct, so it will give an error.

With defaultdict()-

program-

import collections

x=collections.defaultdict(object)
print(x['a'])


output-

<'object object at 0x0000022EB431C740>


-In this program, we use defaultdict() function to create a dictionary, which not give an error while searching a key value from the dictionary.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!