1

I have a python dictionary with 2 lists like below

dict_ans={'Car':[['Toyota', 'Honda'], ['Ford','GM']],
          'Truck':['Kenworth', 'Mack']
         }

I am trying to get it in the format below:

dict_ans={'Car':['Toyota', 'Honda','Ford','GM'],
          'Truck':['Kenworth','Mack']
         }

I tried a few options in the link https://stackabuse.com/python-how-to-flatten-list-of-lists But in each case the 'Truck' resolves to ['K','e','n','w','o','r','t','h','M','a','c','k'] The Car entry worked fine. Any thoughts on the best way to achieve this? Thanks!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
FlyingPickle
  • 1,047
  • 1
  • 9
  • 19

2 Answers2

1

Try dictionary comprehension with numpy.hstack

import numpy as np

new_dict = {k:np.hstack(v).tolist() for k,v in dict_ans.items()} 
# {'Car': ['Toyota', 'Honda', 'Ford', 'GM'], 'Truck': ['Kenworth', 'Mack']}
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41
  • 1
    You don't need to rebuild the dict or even rebind the values, since lists are mutable. `for v in dict_ans.values(): v[:] = np.hstack(v)` – wjandrea Jun 24 '21 at 19:28
0

Maybe a custom function and dict comprehension?

def flatten(x):
    if isinstance(x, list):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]
>>> {k: flatten(dict_ans[k]) for k in dict_ans}
{'Car': ['ToyotaHonda', 'Ford', 'GM'], 'Truck': ['Kenworth', 'Mack']}
not_speshal
  • 22,093
  • 2
  • 15
  • 30