harshit
harshit

Reputation: 7951

Create a list of defaultdict in python

I am doing the following :

recordList=[lambda:defaultdict(str)]
record=defaultdict(str)
record['value']='value1'
record['value2']='value2'
recordList.append(record)
for record in recordList:
    params =  (record['value'],record['value2'],'31')

i am getting the error :

TypeError: 'function' object is not subscriptable

what is wrong here ?

Upvotes: 0

Views: 2082

Answers (3)

poke
poke

Reputation: 387677

recordList=[lambda:defaultdict(str)]

creates a list with a function that returns defaultdict(str). So it's basically equivalent to:

def xy ():
    return defaultdict(str)

recordList = []    
recordList.append( xy )

As such, when you start your for loop, you get the first element from the list, which is not a list (as all the other elements you push to it), but a function. And a function does not have a index access methods (the ['value'] things).

Upvotes: 3

yan
yan

Reputation: 20982

you're adding a lambda to recordList, which is of type 'function'. in the for .. loop, you're trying to subscript it (record['value'], record['value2'], etc)

Initialize recordList to an empty list ([]) and it will work.

Upvotes: 1

Marco
Marco

Reputation: 1346

recordList is a list with 1 element which is a function.

If you replace the first line with

recordList = []

the rest will wor.

Upvotes: 2

Related Questions