从CSV文件创建字典



我需要从csv文件创建一个字典。CSV看起来像这样:

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

我需要创建字典,以便主机名是密钥。类似这样的东西:

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

做这件事最简单的方法是什么?

没有Pandas的替代方案(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}

结果:

{'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'}}
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")

产生

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

相关内容

  • 没有找到相关文章

最新更新