我有一个像这样的二维数组:
main_array -> [object,object,object,....]
each object -> [ var_some_string,parent_id,some_random_int] -> fixed length
我需要将此数组转换为json
这样的对象..
{ var_some_string: { var_some_string : { var_some_string: -1}}}
parent_id是main_array对象位置,它是当前对象的父级
我希望这个问题是可以理解的。
main_array = [
["some_string0",-1,1],
["some_string1",-1,1] ,
["some_string2",-1,1] ,
["some_string3",0,-1],
["some_string4",0,-1],
["some_string5",0,-1],
["some_string6",1,-1],
["some_string7",1,-1],
["some_string8",2,-1],
["some_string9",5,-1],
["some_string10",7,-1],
["some_string11",9,-1],
]
json
对象就是这个
main_json = {
'some_string0' : {
'some_string3' : -1000,
'some_string4' : -1000,
'some_string5' : {
'some_string9' : {
'some_string11' : -1000
},
},
},
'some_string1' : {
'some_string6' : -1000,
'some_string7' : {
'some_string10' : -1000,
}
}
'some_string2' : {
'some_string8' : -1000
}
}
我正在敲打着如何解决这个问题...
答案 0 :(得分:3)
def replace_empty_dict_with(d, value):
for k, v in d.iteritems():
if len(v) == 0:
d[k] = value
else:
replace_empty_dict_with(v, value)
d = {}
w = {}
for node, pid, _ in main_array:
if pid == -1:
w[node] = d[node] = {}
else:
parent = main_array[pid][0]
w[node] = w[parent][node] = {}
replace_empty_dict_with(d, -1)
import pprint
pprint.pprint(d)
输出:
{'some_string0': {'some_string3': -1,
'some_string4': -1,
'some_string5': {'some_string9': {'some_string11': -1}}},
'some_string1': {'some_string6': -1, 'some_string7': {'some_string10': -1}},
'some_string2': {'some_string8': -1}}
答案 1 :(得分:0)
我理解这项任务有点不同。我认为some_random_int应该成为最终字典中的值(不一定是-1)。
main_json = {}
id_to_dict_reference = {
-1: main_json
}
id_to_container = {}
id_to_key_name = {}
for id, (var_some_string, parent_id, some_random_int) in enumerate(main_array):
id_to_key_name[id] = var_some_string
dict_reference = id_to_dict_reference[parent_id]
if dict_reference is None:
parent_container = id_to_container[parent_id]
key_name = id_to_key_name[parent_id]
if not isinstance(parent_container[key_name], dict):
parent_container[key_name] = {}
parent_container[key_name][var_some_string] = some_random_int
id_to_dict_reference[id] = None
id_to_container[id] = parent_container[key_name]
id_to_dict_reference[parent_id] = parent_container[key_name]
else:
dict_reference[var_some_string] = some_random_int
id_to_container[id] = dict_reference
id_to_dict_reference[id] = None
print main_json
输出:
{'some_string0': {'some_string3': -1,
'some_string4': -1,
'some_string5': {'some_string9': {'some_string11': -1}}},
'some_string1': {'some_string6': -1, 'some_string7': {'some_string10': -1}},
'some_string2': {'some_string8': -1}}