Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python collections.defaultdict with list of length two

I have a situation where a key will have two values which will be updated during the program. More conretely, starting from a empty dictionary d = {}, I would like to do some thing like this: d[a][0] += 1 or d[a][1] += 1 where a is a float type which is also found while the program is running. Can I do something to the effect of d = defaultdict(list([0,0])) (this gives error).I want the default values in the dictionary to be a list of two elements. How do I do this?

like image 699
DurgaDatta Avatar asked Feb 25 '13 05:02

DurgaDatta


1 Answers

Just read the documentation:

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

That is, the argument to defaultdict is not the default value, it is a function that is called to produce the default value. So just do:

defaultdict(lambda: [0,0])

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

like image 84
BrenBarn Avatar answered Sep 18 '22 23:09

BrenBarn