-1

Trying to parse a defaultdict(list)

Input:

defaultdict(class <'list'>,{'key1': ['v1', 'v2'], 'key2': [v3, v4], 'key3': ['v5', 'v6']})

desired output:

list_dic = [{key1: v1, key2: v3, key3: v5}, {key1: v2, key2: v4, key3: v6}] 

Has to work for n values in the lists.

Following from the desired output, I intend to use mysql executemany to insert these values into a db. If anyone has any better suggestions of how I could insert a deafaultdict(list) into a table in mysql - I'd appreciate it.

Bob
  • 5
  • 2

1 Answers1

0

For me the answer lies in dic comprehension nested in list comprehension . Please note that this piece of code relies on the input specificaly being a dictionnary with all the list being of the same length !

To test that , please run :

n = len(list(input.values())[0]
all_length_equal = all([len(v)==n for v in input.values()])

Once that is done, the code below goes through each value , picking up the i-value , and stores is into a dictionnary, try it with 0 :

{k:v[0] for k,v in input.items()}

Then you need to add a list comprehension

[ i for for i in range(len(list(input.values())[0])]

The above will return a range of number. But if you combine the two, it will return the dictionnaries with i in range of the length of the first value.

list_dic = [{
     k:v[i] for k,v in input.items() #This create the correct dictionnary with all the i-values in the input
} for i in range(len(list(input.values())[0])] # iterate through the length of the first list
Born Tbe Wasted
  • 610
  • 3
  • 13
  • returns IndexError: list index out of range, could you please go in depth – Bob Mar 29 '19 at 09:48
  • That should mean that you have a list that is not the same length :/ – Born Tbe Wasted Mar 29 '19 at 10:17
  • I got it, my original dict has one value entry that was len 4 but the rest were len 2. So I ran del dict[key] as it's not necessary and then ran your code and it worked - thank you for your patience! – Bob Mar 29 '19 at 10:38