vkaul11
vkaul11

Reputation: 4214

how to have a defaultdict or dictionary with a fixed list or array size as the value

I was trying to use d = defaultdict(array.array) or d = defaultdict(list) for the dictionary, but I dont't know how I can fix the number of elements in the array.array or list to N where N is the size of the array I always want the list or array.array to be. If possible I want all of the N elements of the list to be pre-initialized to zero.

Upvotes: 3

Views: 3497

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208415

The argument to defaultdict() is a callable that creates the default value, so just create a function that creates your starting value:

N = 8  # change N to whatever you want
def default_list():
    return [0] * N

d = defaultdict(default_list)

Or as a lambda:

d = defaultdict(lambda: [0] * N)

Upvotes: 9

icktoofay
icktoofay

Reputation: 129001

You pass defaultdict a function which returns a value, so just give it a function that returns a list or array of the appropriate size. For example:

def make_list_of_10_zeroes():
    return [0] * 10

d = defaultdict(make_list_of_10_zeroes)

Since the function we're using here has only one statement which is a return, we can use a lambda instead:

d = defaultdict(lambda: [0] * 10)

Upvotes: 2

Related Questions