0

I want to convert a dictionary like;

{'Application1': [nodename1, nodetier1, nodeid1],
 'Application2': [nodename2, nodetier2, nodeid2, nodename3, nodetier3, nodeid3]}

to excel format where the dictionary key is printed multiple times for each 3 items. Ideally it would look like;

   Application    nodename    nodetier    nodeid
0  Application1   nodename1   nodetier1   nodeid1
1  Application2   nodename2   nodetier2   nodeid2
2  Application2   nodename3   nodetier3   nodeid3
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Pandas has a function called: to_excel() Curious if you have tried that? https://stackoverflow.com/questions/34183004/how-to-write-a-dictionary-to-excel-in-python – Steven M May 28 '20 at 22:02
  • 1
    You can import csv files into excel https://docs.python.org/3/library/csv.html#csv.DictWriter – HackLab May 28 '20 at 22:04

1 Answers1

0

check this:

import pandas as pd

x = {
    'app1': [0, 1, 2],
    'app2': [0, 1, 2, 3, 4, 5],
    'app3': [0, 1, 2, 3, 4, 5, 6, 7, 8]
}

temp = []
for app in x:
    # chunk the list by the length of 3
    chunks = [x[app][i:i+3] for i in range(0, len(x[app]), 3)]
    # for all chunks add the value with the app name
    for chunk in chunks:
        temp.append(
            [app, *chunk]
        )

df = pd.DataFrame(temp, columns=('application', 'nodename', 'nodetier', 'nodeid'))

print(df)

gives:

  application  nodename  nodetier  nodeid
0        app1         0         1       2
1        app2         0         1       2
2        app2         3         4       5
3        app3         0         1       2
4        app3         3         4       5
5        app3         6         7       8

And finally write to excel file:

df.to_excel('excel_file')
Alireza
  • 656
  • 1
  • 6
  • 20