Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dictionary from CSV file

I need to create a dictionary from a csv file. CSV would look something like this:

hostnames,device_platform,device_role
co-agg-r1,cisco_ios,co-agg-r
co-edg-fw,cisco_asa,co-edg-fw
co-acc-sw,cisco_ios,co-acc-sw
co-acc-rsw,broadcom_icos,co-acc-rsw

I need the dictionary to be created so that the hostnames are the keys. Something like this:

devices_dict = {
 'co-agg-r1': { 'device_platform': 'cisco_ios', 'device_role': 'co-agg-r'},
 'co-edg-fw': { 'device_platform': 'cisco_asa', 'device_role': 'co-edg-fw'},
 'co-acc-sw1': { 'device_platform': 'cisco_ios', 'device_role': 'co-acc-sw'},
 'co-acc-rsw1': { 'device_platform': 'broadcom_icos', 'device_role': 'co-acc-rsw'}
}

What’s the easiest way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import pandas as pd
df = pd.read_csv("/tmp/data.csv")  # data you provided
df.set_index("hostnames").T.to_dict()  # or df.set_index("hostnames").to_dict("index")

yields

{'co-agg-r1': {'device_platform': 'cisco_ios', 'device_role': 'co-agg-r'},
 'co-edg-fw': {'device_platform': 'cisco_asa', 'device_role': 'co-edg-fw'},
 'co-acc-sw': {'device_platform': 'cisco_ios', 'device_role': 'co-acc-sw'},
 'co-acc-rsw': {'device_platform': 'broadcom_icos',
  'device_role': 'co-acc-rsw'}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading