Home > OS >  Stuck trying to create new dictionary from 2 lists - 1 of tuples, 1 for dictionary keys
Stuck trying to create new dictionary from 2 lists - 1 of tuples, 1 for dictionary keys

Time:11-13

I have 2 lists. a is a list of tuples that I would like to transform into a dictionary that retains 'a' values as lists - using the second list as the dictionary keys. I've tried using the a's first set as 'index' values in the tuple list to marry to the 'key' values in the b list. This is what I have:

a = [(0, ['Potato'], [8]),
     (0, ['Tomato'], [2]),
     (0, ['Tomato'], [2]),
     (0, ['Potato'], [6]),
     (0, ['Potato'], [12]),
     (0, ['Potato'], [12]),
     (0, nan, nan),
     (1, [], []),
     (1, [], [])]

b = [('foo', 123), ('bar', 456)]

This is what I'm trying to get:

newDict = {'foo' : [(['Potato'], ['Tomato'], ['Tomato'], ['Potato'], ['Potato'], ['Potato'], nan), ([8], [2], [2], [6], [12], [12], nan)], 
           'bar' : [([], []),([],[])]}

I've tried enumerating through various for loops, unzipping the tuples.

CodePudding user response:

You can use group by (from itertools) to group the tuples from a based on their first entry, then zip that to b to pair up the 'foo' and 'bar' with the corresponding 0 and 1 groups:

a = [(0, ['Potato'], [8]),
     (0, ['Tomato'], [2]),
     (0, ['Tomato'], [2]),
     (0, ['Potato'], [6]),
     (0, ['Potato'], [12]),
     (0, ['Potato'], [12]),
     (0, 'nan', 'nan'),
     (1, [], []),
     (1, [], [])]

b = [('foo', 123), ('bar', 456)]


from itertools import groupby

r = {tb[0]:list(zip(*ta))[1:] for tb,(_,ta) in zip(b,groupby(a,lambda t:t[0]))}

print(r)
{'foo': 
  [(['Potato'], ['Tomato'], ['Tomato'], ['Potato'], ['Potato'], ['Potato'], 'nan'), 
   ([8], [2], [2], [6], [12], [12], 'nan')], 
 'bar': 
  [([], []), ([], [])]}
  • Related