5

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 ?

1
  • @Austin, this would make the code a bit untidy, as after every new key insert, I would have to first append two lists.. extra if checks here..
    – midi
    Commented Nov 11, 2018 at 18:22

2 Answers 2

3

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]]})
0

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])
3
  • Strangely, dict['This'][0].append(1) does not work! what am I missing ?
    – midi
    Commented Nov 11, 2018 at 18:23
  • This works : dict = defaultdict(lambda : [[], []]) but this does not dict = defaultdict(lambda : [list, list]) Cannot figure out why..
    – midi
    Commented Nov 11, 2018 at 18:27
  • 1
    @midi where you write list, it doesn’t get called so you should write either [] or list()
    – N Chauhan
    Commented Nov 11, 2018 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.