This should give you the nested structure you want.
If you want every nested dictonary, also available from the root. Uncomment the if .. is not root
parts
def parse(data):
root = {}
currentDict = root
prevLevel = -1
parents = []
for line in data:
if line.strip() == '': continue
level = len(line) - len(line.lstrip(" "))
key, value = [val.strip() for val in line.split(':', 1)]
if level > prevLevel and not len(value):
currentDict[key] = {}
# if currentDict is not root:
# root[key] = currentDict[key]
parents.append((currentDict, level))
currentDict = currentDict[key]
prevLevel = level
elif level < prevLevel and not len(value):
parentDict, parentLevel = parents.pop()
while parentLevel != level:
if not parents: return root
parentDict, parentLevel = parents.pop()
parentDict[key] = {}
parents.append((parentDict, level))
# if parentDict is not root:
# root[key] = parentDict[key]
currentDict = parentDict[key]
prevLevel = level
else:
currentDict[key] = value
return root
with open('data.txt', 'r') as f:
data = parse(f)
#for pretty print of nested dict
import json
print json.dumps(data,sort_keys=True, indent=4)
output:
{
"Chassis 1": {
"PSU 1": {
"HW Revision": "0",
"Presence": "Equipped",
"VID": "V00"
},
"Servers": {
"Server 1/1": {
"Acknowledged Adapters": "1",
"Acknowledged Cores": "16",
"Equiped PID": "e63-samp-33",
"Equipped Product Name": "EEE UCS B200 M3",
"Equipped VID": "V01"
}
}
}
}