Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs

>>> from collections import defaultdict 

>>> s = 'mississippi' 

>>> d = defaultdict(int) 

>>> for k in s: 

... d[k]+= 1 

... 

>>> d.items() 

[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

and

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] 

>>> d = defaultdict(list) 

>>> for k, v in s: 

... d[k].append(v) 

... 

>>> d.items() 

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

the parameters int and list are for what?

1 Answer

0 votes
by (106k points)

In Python, defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.

See the example:

somedict = {} 

print(somedict[3]) 

someddict = defaultdict(int) 

print(someddict[3])

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
4 answers
0 votes
4 answers
0 votes
1 answer

Browse Categories

...