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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With