Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert a list of dictionary into a table

I have this list of sub dictionaries:

my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5}
 {'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]

I want a print it as a table:

type  |prob|x_sum|y_sum
type_1|2   |3    |5
type_2|3   |8    |6

I tried this solution :

for row in zip(*([key] + value for key, value in sorted(my_dict.items()))):
print(*row)

but got error: AttributeError: 'list' object has no attribute 'items' How I can fix the list problem?

like image 989
KKK Avatar asked Nov 22 '25 14:11

KKK


2 Answers

Easiest is to use Pandas as described Convert list of Dictionaries to Dataframe

Code

import pandas as pd

my_dict = [ {'type' : 'type_1', 'prob' : 2, 'x_sum' : 3, 'y_sum' : 5},
 {'type' : 'type_2', 'prob' : 3, 'x_sum' : 8, 'y_sum' : 6}]

df = pd.DataFrame(my_dict)
print(df)

Output

     type  prob  x_sum  y_sum
0  type_1     2      3      5
1  type_2     3      8      6

Without Index Column

df_no_indices = df.to_string(index=False)
print(df_no_indices)

Output

  type  prob  x_sum  y_sum
 type_1     2      3      5
 type_2     3      8      6

Other Format Examples

Source

PostSQL

from tabulate import tabulate
pdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='psql')
print(pdtabulate(df))

+----+--------+--------+---------+---------+
|    | type   |   prob |   x_sum |   y_sum |
|----+--------+--------+---------+---------|
|  0 | type_1 |      2 |       3 |       5 |
|  1 | type_2 |      3 |       8 |       6 |
+----+--------+--------+---------+---------+

HTML

pdtabulate=lambda df:tabulate(df,headers='keys',tablefmt='html')
print(pdtabulate(df))

<table>
<thead>
<tr><th style="text-align: right;">  </th><th>type  </th><th style="text-align: right;">  prob</th><th style="text-align: right;">  x_sum</th><th style="text-align: right;">  y_sum</th></tr>
</thead>
<tbody>
<tr><td style="text-align: right;"> 0</td><td>type_1</td><td style="text-align: right;">     2</td><td style="text-align: right;">      3</td><td style="text-align: right;">      5</td></tr>
<tr><td style="text-align: right;"> 1</td><td>type_2</td><td style="text-align: right;">     3</td><td style="text-align: right;">      8</td><td style="text-align: right;">      6</td></tr>
</tbody>
</table>
like image 118
DarrylG Avatar answered Nov 25 '25 06:11

DarrylG


you can use:

from collections import defaultdict

r = defaultdict(list)
for d in my_dict:
    for k, v in d.items():
        r[k].append(v)

print('|'.join((e.ljust(7) for e in d.keys())))

print('\n'.join(('|'.join(str(e).ljust(7) for e in t) for t in zip(*r.values()) )))

output:

type   |prob   |x_sum  |y_sum  
type_1 |2      |3      |5      
type_2 |3      |8      |6 
like image 39
kederrac Avatar answered Nov 25 '25 06:11

kederrac