简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM