3

hope you can help me with this.

I have a nested dictionary like this:

Inventory = {'devicename': {'Interface1': {'port_setting1': 'value', 'port_setting2': 'value'}, 'Interface2': {'port_setting1': 'value', 'port_setting2': 'value'}}}

I want to create a csv out of that with the following format:

devicename, interface1, value of port_setting1, value of portsetting2
devicename, interface2, value of port_setting1, value of portsetting2

Can you help me how to handle this?

Thanks!

buran
  • 13,682
  • 10
  • 36
  • 61
nouse4it
  • 33
  • 4

2 Answers2

1

You can import the dictionary to a pandas dataframe. This can then be exported as a csv without the column names to achieve what you require.

The following code snippet would do the trick:

import pandas as pd

df = pd.DataFrame.from_dict({(i,j): Inventory[i][j] 
                           for i in Inventory.keys() 
                           for j in Inventory[i].keys()},
                       orient='index')
df.to_csv('test.csv', header = False)

This is how your test.csv looks like for the dictionary called Inventory you have shown in the question:

devicename,Interface1,value,value
devicename,Interface2,value,value
Ishwar Venugopal
  • 872
  • 6
  • 17
  • Do you know why Panda formats a single decimal value like 90 to 90.0 in the csv? – nouse4it Feb 11 '21 at 13:20
  • Not sure. Maybe because one column would have a single datatype (like `int` or `float`). Check this thread to see how to change datatypes of a column: https://stackoverflow.com/questions/21291259/convert-floats-to-ints-in-pandas – Ishwar Venugopal Feb 11 '21 at 14:25
1

You can loop through the dict and print in a file:

with open(filename.csv, 'w') as fh:
    for k, v in Inventory.items():
        for k1, v1 in v.items():
            print(k, k1, *v1.values(), file=fh, sep=', ')

Or in a comprehension:

with open(filename.csv, 'w') as fh:
    print(*(', '.join((k, k1, *v1.values())) 
           for k, v in Inventory.items() 
           for k1, v1 in v.items()), 
           file=fh, sep='\n'
     )

Output:

devicename, Interface1, value, value
devicename, Interface2, value, value
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52