Search code examples
pythonstringdictionarycollectionsdefaultdict

defaultdict with multiple parameters


I have a defaultdict initialized as:

w2i = defaultdict(lambda: len(w2i))
UNK = w2i["<unk>"]

So UNK will have value 0. Now I add some more elements(words) to w2i with each key being mapped to the length of the dictionary at that instance.

Then if we perform:

w2i = defaultdict(lambda: UNK, w2i)

and try to access w2i with new or existing word keys, what will the result be? e.g. let's say "one" is a key existing in w2i and "two" is not in w2i. After redefining w2i as above what will the result of the following be?

onew2i = w2i["one"]
twow2i = w2i["two"]

Also, what do the 2 parameters in defaultdict represent. Most tutorials on defaultdict with lambda seem to have just 1 parameter.

Thanks!


Solution

  • If you are using:

    w2i = defaultdict(lambda: UNK, w2i)
    

    to add words from a test dataset the words existing in w2i will be skipped, those not in w2i will be added with value 0(UNK).

    So onew2i's value won't be changed, twow2i will have value 0.