如何将嵌套字典转换为矩阵列表?

How to convert a nested dictionary into matrix list?

我有以下词典

dictionary = {'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}}

我希望输出为

[['', 'apple', 'banana', 'lemon', 'grape'],
['test1.txt',1,1,1,0],
['test2.txt',1,1,0,0],
['test3.txt',1,0,2,0],
['test4.txt',1,0,1,1]]

我正在尝试的方法是

testcasenumber = dictionary.keys()  // here i got all the test.txts

我是 python 的新手,有点卡在如何继续我的解决方案上。

首先你会得到所有的列名:

from collections import ChainMap
header = ["", *ChainMap(*d.values())]

然后你可以写一个for循环:

result = [header]
for k, v in d.items(): 
    row = [v.get(h, 0) for h in header] 
    row[0] = k 
    result.append(row)

您是否考虑过使用通用 pandas 库?

from pandas import DataFrame

dictionary = {'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}}

df = DataFrame(dictionary).fillna(0).transpose()
result = [['']+list(df.columns)] + list([idx, *values] for idx, values in zip(df.index, df.values.astype(int).tolist()))
print(result)

结果:

[['', 'apple', 'banana', 'lemon', 'grape'], ['test1.txt', 1, 1, 1, 0], ['test2.txt', 1, 1, 0, 0], ['test3.txt', 1, 0, 2, 0], ['test4.txt', 1, 0, 1, 1]]]