yezy
yezy

Reputation: 49

How to convert a nested dictionary into matrix list?

i have the following dictionary

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}}

i want the output to be

[['', '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]]

The way i am trying is that

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

i am new to python and kinda stuck in how to proceed forward with my solution.

Upvotes: 0

Views: 416

Answers (2)

Grismar
Grismar

Reputation: 31339

Have you considered using the common pandas library?

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)

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]]]

Upvotes: 1

wim
wim

Reputation: 362806

First you would get all the column names:

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

And then you can just write a for-loop:

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

Upvotes: 1

Related Questions