As a simplified example, suppose I have the following dictionary that tells me the number of employees in different locations of a company:
start_dict = {
"/BUILDING_A/FLOOR_3/ROOM_12": 3,
"/BUILDING_A/FLOOR_3/ROOM_15": 4,
"/BUILDING_A/FLOOR_4/ROOM_3": 2,
"/BUILDING_B/FLOOR_1": 5,
"/BUILDING_B/FLOOR_2": 3,
"/BUILDING_C": 25,
"/BUILDING_D": 32,
}
Each dictionary key is a string with one or more slash-separated elements. In my real data each key can contain an arbitrary amount of elements.
I'm looking to convert this start dictionary into a nested dictionary. The desired result would look as follows:
{
"BUILDING_A": {
"FLOOR_3": {
"ROOM_12": 3,
"ROOM_15": 4,
},
"FLOOR_4": {
"ROOM_3": 2
},
},
"BUILDING_B": {
"FLOOR_1": 5,
"FLOOR_2": 3,
},
"BUILDING_C": 25,
"BUIDLING_D": 32,
}
Tried thus far
I have tried to adapt this answer, but can't quite get it to work. This is the code that I came up with:
result_dict = {}
for key, value in start_dict.items():
new_keys = key.lstrip("/").split("/")
current_dict = result_dict
for new_key in new_keys[:-1]:
current_dict = current_dict.get(new_key, {})
current_dict[new_keys[-1]] = value
which gives the following as result_dict:
{'BUILDING_C': 25, 'BUILDING_D': 32}