【问题标题】:How to convert a nested dictionary into matrix list?如何将嵌套字典转换为矩阵列表?
【发布时间】:2021-03-02 10:21:50
【问题描述】:

我有以下字典

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 新手,有点卡在如何继续我的解决方案。

【问题讨论】:

  • 一个简单的谷歌搜索会产生很多结果。例如,geeksforgeeks.org/python-flatten-nested-dictionary-to-matrix
  • 感谢您的建议,我检查了但发现有点不同
  • 我同意你的观点,我可以添加完整的信息,对不起,如果我再次发布问题,我一定会保留你的所有建议并以更有效的方式写作.

标签: python list multidimensional-array nested-lists


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    您是否考虑过使用通用的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]]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2022-12-05
      • 2017-07-29
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多