Variant Of Defaultdict For Assigning Value Only Once
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
defaultdictthat i can use to avoid the checkif 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
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.itertools.count()returns iterator that counts from 0 to infinity.__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"