我的詞典列表如下,創建詞典列表包含嵌套詞典
[{"vehicle_class": "c1", "vehicle_class_count1": 16, "vehicle_usage_count1": 29, "vehicle_usage": "u1", "vehicle_type_count1": 16, "vehicle_type": "t1"}, {"vehicle_class": "c2", "vehicle_class_count1": 11, "vehicle_usage_count1": 29, "vehicle_usage": "u1", "vehicle_type_count1": 11, "vehicle_type": "t1"},{"vehicle_class": "c2", "vehicle_class_count1": 1, "vehicle_usage_count1": 29, "vehicle_usage": "u2", "vehicle_type_count1": 1, "vehicle_type": "t3"},{"vehicle_class": "c3", "vehicle_class_count1": 1, "vehicle_usage_count1": 29, "vehicle_usage": "u2", "vehicle_type_count1": 1, "vehicle_type": "t2"}]
從中我想形成字典的另一個列表如下,
[
{
"name": "u1",
"imageURL": "",
"type": "u1",
"children": [
{
"name": "t1",
"imageURL": "",
"type": "t1",
"size": 9221
"children" : [
{"name": "c1",
"imageURL": "",
"type": "c1",
"size": 9221},
{"name": "c2",
"imageURL": "",
"type": "c2",
"size": 9221}
]
}
],
"size": 10393
},
{
"name": "u2",
"imageURL": "",
"type": "u2",
"children": [
{
"name": "t2",
"imageURL": "",
"type": "t2",
"size": 9221,
"children":[
"name": "c3",
"imageURL": "",
"type": "c3",
"size": 9221
]
},
{
"imageURL": "",
"type": "t3",
"name": "t3",
"size": 1058,
"children": [
"imageURL": "",
"type": "c2",
"name": "c2",
"size": 1058
]
}
],
"size": 10393
},
]
這是我迄今爲止所嘗試過的,我曾經得到了預期結果的一半。
result_dict=[] # The above mentioned list comes here
result_list = []
for i in ['vehicle_usage','vehicle_type','vehicle_class']: # This is a hierarchy which I assign here dynamically can contain any number of values.
for item in range(0, len(result_dict)):
for key,value in result_dict[item].items():
if key == i:
if not any(d['name'] == value for d in result_list):
result = {}
result['name'] = value
result['imageURL'] = ''
result['type'] = value
result['size'] = result_dict[item]['%s_count1' % i]
if i != len(result_dict):
result['children'] =[]
print result
result_list.append(result)
print result_list # Final list processed according to the required format.
預計result_list頂尖水平字典必須包含像vehicle_usage_count1
各自的值vehicle_usage
不同的值。
第二級別(即兒童名單)將包含第二級別等。該數據發送到需要此格式的d3插件。
水平將依賴於價值數數前來
['vehicle_usage','vehicle_type','vehicle_class']
從我的代碼的所有級別寫入到同一水平。我希望他們寫入正確的兒童名單。
那麼,你的代碼只嘗試'result_list.append(結果)'所以很明顯,這一切都在同一水平上。 – abrunet
@abrunet是的,但我怎麼能說,去相關的兒童節點? –
您應該嘗試從初始詞典中提取數據,迭代一次以提取第一級數據。然後迭代你創建的第一級,併爲你的第一級的每個元素,從你的初始詞典等檢索數據... – abrunet