Skip to content Skip to sidebar Skip to footer

Variant Of Defaultdict For Assigning Value Only Once

I am trying to create a dictionary of words with words hashed to an integer for further processing. Is there a variant of defaultdict that i can use to avoid the check if word not

Solution 1:

Here's a simpler and faster way to get what you want:

from itertools import count

wordid = dict(zip(set(sentencewords), count(1)))

This uses a set to obtain the unique words in sentencewords, pairs each of those unique words with the next value from count() (which counts upwards), and constructs a dictionary from the results.

Solution 2:

Is there a variant of defaultdict that i can use to avoid the check if word not in wordid?

Yes, just pass itertools.count().__next__ to its constructor:

>>>from collections import defaultdict>>>from itertools import count>>>dct = defaultdict(count().__next__)>>>dct['anything']
0
>>>dct['test']
1

Explanation

  1. defaultdict's first parameter is callable. When you try to get nonexistent key, it calls this callable without arguments and returns the result. The result is also stored in the defaultdict – when you try to get that item again, it already exist, and you get the same value as before.

  2. itertools.count() returns iterator that counts from 0 to infinity.

  3. __next__ is iterator's method that obtains next element from iterator.

So, basicly, itertools.count().__next__ is callable that returns next natural number each time it's called.

Post a Comment for "Variant Of Defaultdict For Assigning Value Only Once"