I have a csv like this:
device,interface,vlan
switch1,ge-0/0/11,vlan1
switch1,ge-0/0/12,vlan1
switch2,ge-0/0/13,vlan10
switch2,ge-0/0/14,vlan20
switch3,ge-0/0/15,vlan1
switch4,ge-0/0/16,vlan12
switch5,ge-0/0/17,vlan11
Which i want to convert into a nested dict which has the switch name as the first key, and interfaces as additional keys.. so for example switch1 would look like this:
d = {"switch1":{'ge-0/0/11':"vlan1",'ge-0/0/12':"vlan1"}}
working with this code i can’t figure out how to make each interface its own key:
In [126]: with open("interfaces.csv") as f:
...: csvfile = csv.DictReader(f)
...: for row in csvfile:
...: d[row['device']] = {row['interface']:row['vlan']}
...:
In [127]: d
Out[127]:
{'switch1': {'ge-0/0/12': 'vlan1'},
'switch2': {'ge-0/0/14': 'vlan20'},
'switch3': {'ge-0/0/15': 'vlan1'},
'switch4': {'ge-0/0/16': 'vlan12'},
'switch5': {'ge-0/0/17': 'vlan11'}}
So its just using the last interface,vlan pair it looped through… how can i achieve this?
>Solution :
You are currently overriding the value during each iteration instead of adding a new key+value pair to your dict. You can easily achieve this with a default dict, so you do not have to create a new dict yourself if it does not yet exist.
from io import StringIO
from collections import defaultdict
import pprint
import csv
txt = """device,interface,vlan
switch1,ge-0/0/11,vlan1
switch1,ge-0/0/12,vlan1
switch2,ge-0/0/13,vlan10
switch2,ge-0/0/14,vlan20
switch3,ge-0/0/15,vlan1
switch4,ge-0/0/16,vlan12
switch5,ge-0/0/17,vlan11"""
d = defaultdict(dict)
with StringIO(txt) as f:
csvfile = csv.DictReader(f)
for row in csvfile:
d[row['device']][row['interface']]=row['vlan']
pprint.pprint(dict(d))
Output:
{'switch1': {'ge-0/0/11': 'vlan1', 'ge-0/0/12': 'vlan1'},
'switch2': {'ge-0/0/13': 'vlan10', 'ge-0/0/14': 'vlan20'},
'switch3': {'ge-0/0/15': 'vlan1'},
'switch4': {'ge-0/0/16': 'vlan12'},
'switch5': {'ge-0/0/17': 'vlan11'}}
Note: I am only casting the default dict to dict in the pprint to be easier on the eyes, you can decide to keep working with the default dict instead.