In Python, I want something like
dict = defaultdict((list,list))
Essentially, with every key I want two lists!
With the above snippet I get the error first argument must be callable. How can I achieve this ?
In Python, I want something like
dict = defaultdict((list,list))
Essentially, with every key I want two lists!
With the above snippet I get the error first argument must be callable. How can I achieve this ?
Give as parameter to defaultdict
a function that creates your empty lists:
from collections import defaultdict
def pair_of_lists():
return [[], []]
d = defaultdict(pair_of_lists)
d[1][0].append(3)
d[1][1].append(42)
print(d)
# defaultdict(<function pair_of_lists at 0x7f584a40b0d0>, {1: [[3], [42]]})
It is not some kind of type inference, you just provide a function that generates default value. While int
, list
, dict
without argument generate 0
, []
, {}
, which is often exploited in defaultdict declaration. Python has no build in constructor function for pair of list etc. So it is as simple as
di = defaultdict(lambda : ([1,2,3], ['a', 'cb']))
While Python allows tuples (pairs) of lists, you might have some issues e.g. with hashing of list tuples. To be safe, you can set deafult to list of two list. Note you have set it to specific lists, empty or not, and not list type/constructor. It is literally about setting default value and not a type declaration - python lists are untyped.
from collections import defaultdict
l1 = []
l2 = ["another", "default", "list"]
di = defaultdict(lambda : [ l1, l2] )
print (di[3])
dict = defaultdict(lambda : [[], []])
but this does not dict = defaultdict(lambda : [list, list])
Cannot figure out why..
list
, it doesn’t get called so you should write either []
or list()
Commented
Nov 11, 2018 at 18:43