pythontabulate

Python convert array of objects with k, v pairs into table


I'm looking for way to convert the beneath list of dicts into a table.

From:

arr = [{'G': ["Apple", "Banana"]}, {'M': ["Orange", "Kiwi"]}, {'P': ["Orange"]}, {'MP': ["All"]}]

To:

User Fruit
G Apple, Banana
M Orange, Kiwi
P Orange
MP All

I'd also like to have the totals of each fruit detailed.

Beneath is my current solution, I'm making use of tabulate

table = tabulate(arr, tablefmt='html')

Any help would be greatly appreciated.


Solution

  • table = tabulate([ [ list(arr[i].keys())[0] , ','.join(arr[i].get(list(arr[i].keys())[0])) ] for i in range(len(arr)) ], tablefmt='html', headers=["User","Fruit"])
    

    try this