I am trying to create a custom nested dict
from a file read in python
without collection
module. My dictionary data structure is bellow.
d = {'employee':
{'developer1':
{'id1':
{'language': ('c', 'java'),
'worked_area':('delhi', 'kolkata')
},
'id2':
{'language':('python' , 'c++'),
'worked_area':('kolkata')
}
},
'devloper2':
{'id1':
{'language': ('c', 'java'),
'worked_area':('delhi', 'kolkata')
}
}
}
}
And reading the data structure using the bellow code:
for k1, v1 in d.items():
for k2, v2 in v1.items():
for k3, v3 in v2.items():
for k4, v5 in v3.items():
print(k1, k2, k3, k4, v5)
The file : text1.txt
employee developer1 id1 language c
employee developer1 id1 language java
employee developer1 id1 worked_area delhi
employee developer1 id1 worked_area kolkata
employee developer1 id2 language python
employee developer1 id2 language c++
employee developer1 id2 worked_area kolkata
employee devloper2 id1 language c
employee devloper2 id1 language java
employee devloper2 id1 worked_area delhi
employee devloper2 id1 worked_area kolkata
Now I am trying to create the above dictionary data structure from the above text file and print its content using the above code.
import re
d = {}
fh = open('text1.txt', 'r')
for i, line in enumerate(fh):
line = line.strip()
tmp = re.split(r'\t+', line)
d[tmp[0]][tmp[1]][tmp[2]][tmp[3]].append(tmp[4])
But I am getting the bellow error while running the code
Error
KeyError: 'employee'
So need help to create the data structure code.