Учитывая ваши исходные данные как:
d = {'test1.txt': {'apple': 1, 'banana': 1, 'lemon': 1},
'test2.txt': {'apple': 1, 'banana': 1},
'test3.txt': {'apple': 1, 'lemon': 2},
'test4.txt': {'apple': 1, 'lemon': 1, 'grape': 1}}
Вы можете получить уникальные значения и немного транспонировать значения, например:
# Get all unique row_labels
keys = set().union(*d.values())
# Build up the rows to include zero values for items not present
rows = [[values.get(key, 0) for key in keys] for values in d.values()]
# Build the table with the header row and then each row_label with
# the transposed version of the values
table = [
['', *d],
*([key, *vals] for key, vals in zip(keys, zip(*rows)))
]
Это даст вам table
как:
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'],
['lemon', 1, 0, 2, 1],
['banana', 1, 1, 0, 0],
['apple', 1, 1, 1, 1],
['grape', 0, 0, 0, 1]]