Creating a DefaultDict with keys which are string, stored in a list

277 Views Asked by At

I have a list of strings, like this:

mylist= [['I', 'am'],['stuck', 'here', 'forever']]

I would like to create a list of dictionaries based on this list in this fashion:

   mydict = [{'I':1, 'am':2},{'stuck':5, 'here':4, 'forever':7}]

Here is what I have tried so far, but it isnt working.

from collections import defaultdict
mydict=defaultdict(str)
mylist= [['I', 'am'],['stuck', 'here', 'forever']]

output = [ [mydict[mylist[i][j]]=len(mylist[i][j])  for j in range(len(mylist[i]))] for i in range(len(mylist))]

But when I stop trying to assign values to my defaultdict, then I am able to access the elements inside the list of lists.

So for example, this works:

[[(mylist[i][j], len(mylist[i][j]))  for j in range(len(mylist[i]))] for i in range(len(mylist))]

and produces this as an output:

[[('I', 1), ('am', 2)], [('stuck', 5), ('here', 4), ('forever', 7)]]
0

There are 0 best solutions below