For example, I want to define a function:
def add_value(dic, path, value):
...
...
return dic
d = {}
d = add_value(d, ['A', 'B'], ('log.txt', '12KB'))
print(d)
d = add_value(d, ['X', 'Y', 'Z'], ('backup.bin', '17MB'))
print(d)
d = add_value(d, ['X', 'Y', 'Z'], ('file.lst', '5KB'))
print(d)
The output should look like this:
{'A': {'B': {'log.txt': '12KB'}}}
{'A': {'B': {'log.txt': '12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB'}}}}
{'A': {'B': {'log.txt':'12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB', 'file.lst': '5KB'}}}}
I tried like this:
import json
def add_value(dic, path, value):
length = len(path)
if length == 1:
if path[0] not in dic:
dic[path[0]] = {}
else:
dic[path[0]].append(value)
return dic
elif length == 2:
if path[0] not in dic:
dic[path[0]] = {}
if path[1] not in dic[path[0]]:
dic[path[0]][path[1]] = {}
dic[path[0]][path[1]][value[0]] = value[1]
return dic
elif length == 3:
if path[0] not in dic:
dic[path[0]] = {}
if path[1] not in dic[path[0]]:
dic[path[0]][path[1]] = {}
if path[2] not in dic[path[0]][path[1]]:
dic[path[0]][path[1]][path[2]] = {}
dic[path[0]][path[1]][path[2]][value[0]] = value[1]
return dic
elif length == 4:
if path[0] not in dic:
dic[path[0]] = {}
if path[1] not in dic[path[0]]:
dic[path[0]][path[1]] = {}
if path[2] not in dic[path[0]][path[1]]:
dic[path[0]][path[1]][path[2]] = {}
if path[3] not in dic[path[0]][path[1]][path[2]]:
dic[path[0]][path[1]][path[2]][path[3]] = {}
dic[path[0]][path[1]][path[2]][path[3]][value[0]] = value[1]
return dic
else:
return
d = {}
d = add_value(d, ['A', 'B'], ('log.txt', '12KB'))
d = add_value(d, ['A', 'B', 'C',], ('log2.txt', '34kb'))
d = add_value(d, ['A', 'G'], ('log2.txt', '2kb'))
d = add_value(d, ['X', 'Y', 'Z'], ('log2.txt', '3kb'))
print(json.dumps(d, indent=2))
and conclusion:
{ "X": {
"Y": {
"Z": {
"log2.txt": "3kb"
}
} }, "A": {
"G": {
"log2.txt": "2kb"
},
"B": {
"C": {
"log2.txt": "34kb"
},
"log.txt": "12KB"
} } }
It seems very stupid. If I want add_value(d, ['A', 'B', 'C', ... , 'Y', 'Z'], ('1.jpg', '1.2MB')), I need to write tons of codes.