Python collections.defaultdict with a list of length two

I have a situation where the key will have two values โ€‹โ€‹that will be updated during the program. More specifically, starting with an empty dictionary d = {}, I would like to do the following: d[a][0] += 1 or d[a][1] += 1 , where a is the type of float, which is also in program run time. Can I do something with the effect d = defaultdict(list([0,0])) (this gives an error). I want the default values โ€‹โ€‹in the dictionary to be a list of two elements. How to do it?

+4
source share
1 answer

Just read the documentation :

If default_factory not None, it is called without arguments to provide a default value for the given key, this value is inserted into the dictionary for the key and returned.

That is, the defaultdict argument is not a default value; it is a function called to get the default value. So simple:

 defaultdict(lambda: [0,0]) 

(There is no need to use list([0,0]) explicitly. [0,0] already a list.)

+11
source

All Articles