Print the list of lists as a grid

Ok, I read all this before, and I think pandas might be the solution, but my problem is a little different:
Printing a dictionary of lists vertically
Printing lists as tabular data
print the values ​​of a dictionary that are inside a list in python
Printing a dictionary into a table

I have a list of lists:

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

As a result, I want:

    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 the value corresponding to A, B, C or (A, in) in another dictionary, but if I can just get the first table, I will be more than happy)

, ( , , , ).

( 0 1 , , pandas DataFrame, , , ), //.

, (pandas, , ?); . .

+4
3

apply 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
+5

( str.format):

def create_table(dictionary, columns):
    column_set = set(columns)  # only to speed up "in" calls, could be omitted
    # Fill in the symbols depending on the presence of the corresponding columns
    filled_dct = {key: [' X' if col in lst else ' -' for col in column_set] 
                  for key, lst in dct.items()}

    # A template string that is filled for each row
    row_template = '   '.join(['{}']*(len(columns)+1))

    print(row_template.format(*([' '] + columns)))
    for rowname, rowcontent in sorted(filled_dct.items()):
        print(row_template.format(*([rowname] + rowcontent)))

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

columns = ['i1', 'i2', 'i3', 'i4', 'i5']

create_table(dct, columns)
    i1   i2   i3   i4   i5
A    X    X    -    -    X
B    X    -    X    X    -
C    X    X    X    -    -

( ..), .

+1

:

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

dict.fromkeys(), dic (aka dic.values()), list dic's (aka dic.keys()).

By understanding the dictionary, the result calculated in the last step will be the values ​​of the data frame. Transport it so that the column headings become the axis of the indices and vice versa.

Fill Nansin later on "-".

pd.DataFrame({k:dict.fromkeys(v,k) for k,v in dic.items()}).T.fillna("-")
#                               ^----- replace k with "x" to get back the first o/p

+1
source

Source: https://habr.com/ru/post/1670509/


All Articles