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

Question:

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.

Asked By: geojoe

||

Answers:

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

Answered By: Abhi747
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.