Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a dict of lists as a grid-layout

Ok, I read all of these before and I think pandas could be a solution, but my problem is slighly different:
Print a dictionary of lists vertically
Printing Lists as Tabular Data
print dictionary values which are inside a list in python
Print a dictionary into a table

I have a dict of lists :

dict={"A":[i1, i2,i3], "B":[i1, i4,i5], "C":[i1, i2,i5]}

What I want as an output is :

    i1    i2    i3    i4    i5   
A    x     x     x     -     -   
B    x     -     -     x     x   
C    x     x     -     -     x  

(or even better,

    i1    i2    i3    i4    i5  
A    A     A     A     -     -  
B    B     -     -     B     B  
C    C     C     -     -     C  

or a value matching A, B, C or (A,in) in another dictionary, but if I can merely have the first table, I'll be more than happy)

No list contains repeats, but every elements in these lists are extracted from a same list (actually my problem is making a grid of annotated terms with the corresponding proteins, the keys being the annotated terms, which are functions related to these proteins in my context of study).

I indeed can think of a convoluted way to do so (building vectors of 0 and 1 for comparison of each list to the general list, associating these vectors with the keys, putting this in a pandas DataFrame which will be well formatted by the magic of me restablishing the good number of entities per list, and print this), but this seems/is tedious/unpythonic.

I think there must be a known way to do that with some module (pandas, prettytable, other?); and that I just don't know it. So I'll be glad for any insight about this. Thanks

like image 549
Ando Jurai Avatar asked Mar 10 '23 19:03

Ando Jurai


1 Answers

apply with a lambda

d = {
    "A": ['i1', 'i2', 'i3'],
    "B": ['i1', 'i4', 'i5'],
    "C": ['i1', 'i2', 'i5']
}

df = pd.DataFrame(d)

df.apply(lambda c: pd.Series(c.name, c.values)).fillna('-').T

  i1 i2 i3 i4 i5
A  A  A  A  -  -
B  B  -  -  B  B
C  C  C  -  -  C
like image 56
piRSquared Avatar answered Mar 20 '23 01:03

piRSquared