Home > Enterprise >  Create a dictionary from CSV file
Create a dictionary from CSV file

Time:03-24

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?

CodePudding user response:

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'}}

CodePudding user response:

Alternative without Pandas (nothing wrong with Pandas):

import csv

with open("file.csv", "r") as file:
    reader = csv.reader(file)
    keys = next(reader)[1:]
    devices_dict = {key: dict(zip(keys, values)) for key, *values in reader}

Result:

{'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'}}
  • Related