Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Python Dictionary to CSV

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!

like image 730
nouse4it Avatar asked Jun 30 '26 10:06

nouse4it


1 Answers

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
like image 150
Ishwar Venugopal Avatar answered Jul 03 '26 00:07

Ishwar Venugopal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!