简体   繁体   中英

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

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.

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': 
  [([], []), ([], [])]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM