Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am new to datascince i am trying to learn it from ebook and i founf this code in it:

dd_pair = defaultdict(lambda: [0, 0])

dd_pair[2][1] = 1                       # now dd_pair contains {2: [0, 1]}

I didn't understand how it works. Can anyone explain this to me?

1 Answer

0 votes
by (36.8k points)

In the code,  defaultdict is a function that takes data type as an initializer default. For example, we have a dictionary named 'user' which contains id as key and list as values. So we are going to check if the directory user has a particular id. if yes then we are going to append something inside the list. If not then we are going to put an empty list.

We can use a directory to perform as shown:

users = {}

if "id1" not in users:

    users["id1"] = []

users["id1"].append("log")

Now using the defaultdic we are going to set the initializer

from collections import defaultdict

users = defaultdict(list)  # Any key not existing in the dictionary will get assigned a `list()` object, which is an empty list

users["id1"].append("log")

Let's come to your code

dd_pair = defaultdict(lambda: [0, 0])

If the key doesn't exists in the ddpair then it gives us 2 elements instead of one. 

So when you print 

print(dd_pair["somerandomkey"])

[0,0]

dd_pair[2][1] would look something like this:

dd_pair[2] = [0,0] # dd_pair looks like: {2:[0,0]}

dd_pair[2][1] = 1  # dd_pair looks like: {2:[0,1]}

Now you may have a doubt why do we need lambda?

The defaultdict constructor expects a callable (The constructor actually expects a default_factory, check out Python docs). In extremely simple terms, if we do defaultdict(somevar), somevar() should be valid.

So, if you just pass [0,0] to defaultdict it'll be wrong since [0,0]() is not valid at all. So what you need is a function which returns [0,0], which can be simply implemented using lambda:[0,0]. (To verify, just do (lambda:[0,0])() , it will return [0,0]).

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 22, 2021 in Python by Rekha (2.2k points)
0 votes
1 answer

Browse Categories

...