I would like to iterate through a set in a constraint. I have built an abstract model. Let's assume the following dictionaries for the instance:
dict_Nodes = {None: ['N1', 'N2']}
dict_Nodes_ArcsOut = {'N1': ['N1N4', 'N1N3'], 'N2': ['N2N5', 'N2N7']}
dict_Time = {None: [0, 1, 2]}
dict_Arcs = {None: ['N1N4', 'N1N3', 'N2N5', 'N2N7']}
However, as I am constructing an abstract model the data should not really matter.
I want to say that the variable in node N1 is the same value as in the arcs N1N4 and N1N3. For the abstract model I created several sets:
from pyomo.environ import AbstractModel, Param, minimize, Var, Constraint,\
SolverFactory, Set, Objective, NonNegativeReals, Reals, Binary, ConstraintList
model = AbstractModel()
model.Set_Nodes = Set()
model.Set_Arcs = Set()
model.Set_Time = Set()
model.Set_Nodes_ArcsOut = Set(model.Set_Nodes)
model.Var_Arc = Var(model.Set_Arcs, model.Set_Time, within=NonNegativeReals)
model.Var_Node = Var(model.Set_Nodes, model.Set_Time, within=NonNegativeReals)
Looking at the data I would like to say that:
Var_Arc['N1N4'] = Var_Node['N1']
Var_Arc['N1N3'] = Var_Node['N1']
Var_Arc['N2N5'] = Var_Node['N2']
Var_Arc['N2N7'] = Var_Node['N2']
To implement the constraint I tried the following two options:
def Arc_rule(model, node, t):
for arc in model.Set_Nodes_ArcsOut[node]:
return model.Var_Arc[arc, t] == model.Var_Node[node, t]
model.ArcInTemp_rule = Constraint(model.Set_Nodes, model.Set_Time, rule=ArcInTemp_rule)
This option only takes the first position of the list. This is probably caused by the return which stops the iteration.
Option 2:
def _init(model):
for t in model.Set_Time:
for node in model.Set_Nodes_ArcsOut:
yield model.Var_Arcs_TempIn[model.Set_Nodes_ArcsOut[node], t] == model.Var_Nodes_TempMix[node, t]
model.init_conditions = ConstraintList(rule=_init)
This does not work and I get the following error: TypeError: unhashable type: '_InsertionOrderSetData'.
I do not understand because I can do this operation if I do a summation. However, iteration seems to be impossible with an abstract model.
I rephrased the problem and illustrated it based on the pyomo example. The tryRule is what I needed:
import pyomo.environ as pyo
model = pyo.AbstractModel()
model.Nodes = pyo.Set()
model.Arcs = pyo.Set(dimen=2)
def NodesOut_init(m, node):
for i, j in m.Arcs:
if i == node:
yield j
model.NodesOut = pyo.Set(model.Nodes, initialize=NodesOut_init)
def NodesIn_init(m, node):
for i, j in m.Arcs:
if j == node:
yield i
model.NodesIn = pyo.Set(model.Nodes, initialize=NodesIn_init)
model.Flow = pyo.Var(model.Arcs, domain=pyo.NonNegativeReals)
model.NodeFlow = pyo.Var(model.Nodes, domain=pyo.NonNegativeReals)
model.FlowCost = pyo.Param(model.Arcs)
model.Demand = pyo.Param(model.Nodes)
model.Supply = pyo.Param(model.Nodes)
def Obj_rule(m):
return pyo.summation(m.FlowCost, m.Flow)
model.Obj = pyo.Objective(rule=Obj_rule, sense=pyo.minimize)
def tryRule(m, i, j):
return m.Flow[i, j] == m.NodeFlow[i]
model.tryRule = pyo.Constraint(model.Arcs, rule=tryRule)
def FlowBalance_rule(m, node):
return m.Supply[node] \
+ sum(m.Flow[i, node] for i in m.NodesIn[node]) \
- m.Demand[node] \
- sum(m.Flow[node, j] for j in m.NodesOut[node]) \
== 0
model.FlowBalance = pyo.Constraint(model.Nodes, rule=FlowBalance_rule)
dict_data = {
None: {
'Nodes': {None: ['CityA', 'CityB', 'CityC']},
'Arcs': {None: [('CityA', 'CityB'), ('CityA', 'CityC'), ('CityC', 'CityB')]},
'FlowCost': {
('CityA', 'CityB'): 1.4,
('CityA', 'CityC'): 2.7,
('CityC', 'CityB'): 1.6,
},
'Demand': {
'CityA': 0,
'CityB': 1,
'CityC': 1,
},
'Supply': {
'CityA': 2,
'CityB': 0,
'CityC': 0,
}
}
}
# create instance
instance = model.create_instance(dict_data)
instance.pprint()
The result for the rule is:
tryRule : Size=3, Index=Arcs, Active=True
Key : Lower : Body : Upper : Active
('CityA', 'CityB') : 0.0 : Flow[CityA,CityB] - NodeFlow[CityA] : 0.0 : True
('CityA', 'CityC') : 0.0 : Flow[CityA,CityC] - NodeFlow[CityA] : 0.0 : True
('CityC', 'CityB') : 0.0 : Flow[CityC,CityB] - NodeFlow[CityC] : 0.0 : True
Related
def calcCandidates(str):
TOKEN_CONFIG = [
("Mor", af.automata_Mor(str))]
for (TokenKind, automata) in TOKEN_CONFIG:
candidates.append(TokenKind)
return (allTrapped, candidates)
I do get a reply and is this:
(False, [])
But I'm expecting to have something inside [], for example ["mor"]
If you need the full code of that function:
def calcCandidates(str):
TOKEN_CONFIG = [
("Mor", af.automata_Mor(str)),
("Si", af.automata_Si(str)),
("Hacer", af.automata_Hacer(str)),
("OpenC", af.automata_OpenC(str)),
("CloseC", af.automata_CloseC(str)),
]
allTrapped = True
candidates = []
for (TokenKind, automata) in TOKEN_CONFIG:
res = automata
if res == RESULT_ACCEPTED:
allTrapped = False
candidates.append(TokenKind)
if res == RESULT_NOT_ACCEPTED:
allTrapped = False
return (allTrapped, candidates)
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.
I tried this:
new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
def approachA():
for data in new_users: # new_users is a list of nested dictionaries
if data == '0':
print("found 0")
keys = data.keys()
for key in keys:
if key == '0':
key.pop() # tried to deleted delete the elements at first
It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.
This is a simple version of what I am trying to do:
[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]
So basically the keys with value "0" get copied to a temp list of dictionaries.
As I mentioned in a comment I'm not sure this will solve your problem, but based on the sample transformation you gave, here's one way to achieve it:
LIST_IN = [{"name": {"book1": "0", "book2": "1", "book3": "0"}}]
def proccess(list_in):
result = []
for this_dict in list_in:
for key in this_dict["name"]:
if this_dict["name"][key] == "0":
result.append({key: this_dict["name"][key]})
return result
print(proccess(LIST_IN))
This should accomplish the "sample" snippet. Please give some additional details if this is not what you were trying.
def solve_nested(nested_dict: list) -> list:
result = list()
for dictionary in nested_dict:
for k, v in dictionary.items():
for _k, _v in v.items():
if _v == '0':
result.append({_k: _v})
return result
if __name__ == '__main__':
print(solve_nested([{"name": {"book1": "0", "book2": "1", "book3": "0"}}]))
If you're interested in recursion, the below example ought to get you going:
# d_xy => x = nest level
# y = dictionary item in nest level x
d = {'d_00' : {'d_10' : {'d_20' : 0,
'd_21' : 43,
'd_22' : 12},
'd_11' : 4,
'd_12' : 0,
'd_13' : 1},
'd_01' : 0,
'd_02' : {'d_14' : {'d_23' : 0,
'd_24' : 1,
'd_25' : 0},
'd_15' : 4,
'd_16' : {'d_26' : 0,
'd_27' : {'d_30' : 3,
'd_31' : 0,
'd_32' : {'d_40' : 0},
'd_33' : 0},
'd_28' : 1},
'd_17' : 0}}
important_items = []
def get_0_key_values(dic):
for key in dic:
if type(dic[key]) == dict:
get_0_key_values(dic[key])
else:
if dic[key] == 0:
important_items.append({key : dic[key]})
get_0_key_values(d)
print(important_items)
here is the mindmap
and corresponding csv file is
history,Africa,Egyptian,pyramid
,Asia,Ancient India,Caste System
,,,Buddhism
,Eourp,Greece,xxx
,,Rome,yyy
,,,zzzz
I want to convert csv file to json like struct
{
'history': [
{
'Africa': [
{
'Egyptian': [{'pyramid': []}]
}
]
},
{
'Asia': [
{
'Ancient India': [
{'Caste System': []},
{'Buddhism': []}
]
}
]
},
...
]
}
finally a function to find the key and print the path of that key
e.g. find('Buddhism') -> history.Asia.Ancient India.Buddhism
I've tried Tree but I have no idea how to achieve this.
Here's a working solution:
# Load your string into list of list
m = []
for each in s.split('\n'):
l = each.split(',')
m.append(l)
# Create dict object that you want.
master = {}
level_indexes = [-1]*10
for i in range(len(m)):
level = len([e for e in m[i] if e == ''])
level_indexes[level] = i
level_indexes[level+1:] = [-1]*(10-level-1)
if level == 0:
head = master
for each in m[i]:
head[each] = {}
head = head[each]
else:
head = master
indexes = []
for j, e in enumerate(level_indexes[:level]):
if e is not -1:
indexes.append(j)
indexes.append(level)
last = []
for j in range(len(indexes)-1):
last.extend(m[level_indexes[j]][indexes[j]:indexes[j+1]])
for j in range(level):
head = head[last[j]]
for j in range(level, len(m[i])):
head[m[i][j]] = {}
head = head[m[i][j]]
This creates a nested dictionary - master:
{'history': {'Africa': {'Egyptian': {'pyramid': {}}},
'Asia': {'Ancient India': {'Buddhism': {}, 'Caste System': {}}},
'Eourp': {'Greece': {'xxx': {}},
'Rome': {'yyy': {}, 'zzzz': {}}}}}
If you tweak it a little bit, you can put everything in list, but that will make it much more complicated:
master = []
level_indexes = [-1]*10
for i in range(len(m)):
level = len([e for e in m[i] if e == ''])
level_indexes[level] = i
level_indexes[level+1:] = [-1]*(10-level-1)
if level == 0:
head = master
for each in m[i]:
head.append({each: []})
head = head[-1][each]
else:
head = master
indexes = []
for j, e in enumerate(level_indexes[:level]):
if e is not -1:
indexes.append(j)
indexes.append(level)
last = []
for j in range(len(indexes)-1):
last.extend(m[level_indexes[j]][indexes[j]:indexes[j+1]])
for j in range(level):
head = head[-1][last[j]]
for j in range(level, len(m[i])):
head.append({m[i][j]: []})
head = head[-1][m[i][j]]
output:
[{'history': [{'Africa': [{'Egyptian': [{'pyramid': []}]}]},
{'Asia': [{'Ancient India': [{'Caste System': []},
{'Buddhism': []}]}]},
{'Eourp': [{'Greece': [{'xxx': []}]},
{'Rome': [{'yyy': []}, {'zzzz': []}]}]}]}]
Search for a value and get the parent dictionary names (keys):
Dictionary = {dict1:{
'part1': {
'.wbxml': 'application/vnd.wap.wbxml',
'.rl': 'application/resource-lists+xml',
},
'part2':
{'.wsdl': 'application/wsdl+xml',
'.rs': 'application/rls-services+xml',
'.xop': 'application/xop+xml',
'.svg': 'image/svg+xml',
},
'part3':{...}, ...
dict2:{
'part1': { '.dotx': 'application/vnd.openxmlformats-..'
'.zaz': 'application/vnd.zzazz.deck+xml',
'.xer': 'application/patch-ops-error+xml',}
},
'part2':{...},
'part3':{...},...
},...
In above dictionary I need to search values like: "image/svg+xml". Where, none of the values are repeated in the dictionary. How to search the "image/svg+xml"? so that it should return the parent keys in a dictionary { dict1:"part2" }.
Please note: Solutions should work unmodified for both Python 2.7 and Python 3.3.
Here's a simple recursive version:
def getpath(nested_dict, value, prepath=()):
for k, v in nested_dict.items():
path = prepath + (k,)
if v == value: # found value
return path
elif hasattr(v, 'items'): # v is a dict
p = getpath(v, value, path) # recursive call
if p is not None:
return p
Example:
print(getpath(dictionary, 'image/svg+xml'))
# -> ('dict1', 'part2', '.svg')
To yield multiple paths (Python 3 only solution):
def find_paths(nested_dict, value, prepath=()):
for k, v in nested_dict.items():
path = prepath + (k,)
if v == value: # found value
yield path
elif hasattr(v, 'items'): # v is a dict
yield from find_paths(v, value, path)
print(*find_paths(dictionary, 'image/svg+xml'))
This is an iterative traversal of your nested dicts that additionally keeps track of all the keys leading up to a particular point. Therefore as soon as you find the correct value inside your dicts, you also already have the keys needed to get to that value.
The code below will run as-is if you put it in a .py file. The find_mime_type(...) function returns the sequence of keys that will get you from the original dictionary to the value you want. The demo() function shows how to use it.
d = {'dict1':
{'part1':
{'.wbxml': 'application/vnd.wap.wbxml',
'.rl': 'application/resource-lists+xml'},
'part2':
{'.wsdl': 'application/wsdl+xml',
'.rs': 'application/rls-services+xml',
'.xop': 'application/xop+xml',
'.svg': 'image/svg+xml'}},
'dict2':
{'part1':
{'.dotx': 'application/vnd.openxmlformats-..',
'.zaz': 'application/vnd.zzazz.deck+xml',
'.xer': 'application/patch-ops-error+xml'}}}
def demo():
mime_type = 'image/svg+xml'
try:
key_chain = find_mime_type(d, mime_type)
except KeyError:
print ('Could not find this mime type: {0}'.format(mime_type))
exit()
print ('Found {0} mime type here: {1}'.format(mime_type, key_chain))
nested = d
for key in key_chain:
nested = nested[key]
print ('Confirmation lookup: {0}'.format(nested))
def find_mime_type(d, mime_type):
reverse_linked_q = list()
reverse_linked_q.append((list(), d))
while reverse_linked_q:
this_key_chain, this_v = reverse_linked_q.pop()
# finish search if found the mime type
if this_v == mime_type:
return this_key_chain
# not found. keep searching
# queue dicts for checking / ignore anything that's not a dict
try:
items = this_v.items()
except AttributeError:
continue # this was not a nested dict. ignore it
for k, v in items:
reverse_linked_q.append((this_key_chain + [k], v))
# if we haven't returned by this point, we've exhausted all the contents
raise KeyError
if __name__ == '__main__':
demo()
Output:
Found image/svg+xml mime type here: ['dict1', 'part2', '.svg']
Confirmation lookup: image/svg+xml
Here is a solution that works for a complex data structure of nested lists and dicts
import pprint
def search(d, search_pattern, prev_datapoint_path=''):
output = []
current_datapoint = d
current_datapoint_path = prev_datapoint_path
if type(current_datapoint) is dict:
for dkey in current_datapoint:
if search_pattern in str(dkey):
c = current_datapoint_path
c+="['"+dkey+"']"
output.append(c)
c = current_datapoint_path
c+="['"+dkey+"']"
for i in search(current_datapoint[dkey], search_pattern, c):
output.append(i)
elif type(current_datapoint) is list:
for i in range(0, len(current_datapoint)):
if search_pattern in str(i):
c = current_datapoint_path
c += "[" + str(i) + "]"
output.append(i)
c = current_datapoint_path
c+="["+ str(i) +"]"
for i in search(current_datapoint[i], search_pattern, c):
output.append(i)
elif search_pattern in str(current_datapoint):
c = current_datapoint_path
output.append(c)
output = filter(None, output)
return list(output)
if __name__ == "__main__":
d = {'dict1':
{'part1':
{'.wbxml': 'application/vnd.wap.wbxml',
'.rl': 'application/resource-lists+xml'},
'part2':
{'.wsdl': 'application/wsdl+xml',
'.rs': 'application/rls-services+xml',
'.xop': 'application/xop+xml',
'.svg': 'image/svg+xml'}},
'dict2':
{'part1':
{'.dotx': 'application/vnd.openxmlformats-..',
'.zaz': 'application/vnd.zzazz.deck+xml',
'.xer': 'application/patch-ops-error+xml'}}}
d2 = {
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{"id": "1001", "type": "Regular"},
{"id": "1002", "type": "Chocolate"},
{"id": "1003", "type": "Blueberry"},
{"id": "1004", "type": "Devil's Food"}
]
},
"topping":
[
{"id": "5001", "type": "None"},
{"id": "5002", "type": "Glazed"},
{"id": "5005", "type": "Sugar"},
{"id": "5007", "type": "Powdered Sugar"},
{"id": "5006", "type": "Chocolate with Sprinkles"},
{"id": "5003", "type": "Chocolate"},
{"id": "5004", "type": "Maple"}
]
},
...
]
}
}
pprint.pprint(search(d,'svg+xml','d'))
>> ["d['dict1']['part2']['.svg']"]
pprint.pprint(search(d2,'500','d2'))
>> ["d2['items']['item'][0]['topping'][0]['id']",
"d2['items']['item'][0]['topping'][1]['id']",
"d2['items']['item'][0]['topping'][2]['id']",
"d2['items']['item'][0]['topping'][3]['id']",
"d2['items']['item'][0]['topping'][4]['id']",
"d2['items']['item'][0]['topping'][5]['id']",
"d2['items']['item'][0]['topping'][6]['id']"]
Here are two similar quick and dirty ways of doing this type of operation. The function find_parent_dict1 uses list comprehension but if you are uncomfortable with that then find_parent_dict2 uses the infamous nested for loops.
Dictionary = {'dict1':{'part1':{'.wbxml':'1','.rl':'2'},'part2':{'.wbdl':'3','.rs':'4'}},'dict2':{'part3':{'.wbxml':'5','.rl':'6'},'part4':{'.wbdl':'1','.rs':'10'}}}
value = '3'
def find_parent_dict1(Dictionary):
for key1 in Dictionary.keys():
item = {key1:key2 for key2 in Dictionary[key1].keys() if value in Dictionary[key1][key2].values()}
if len(item)>0:
return item
find_parent_dict1(Dictionary)
def find_parent_dict2(Dictionary):
for key1 in Dictionary.keys():
for key2 in Dictionary[key1].keys():
if value in Dictionary[key1][key2].values():
print {key1:key2}
find_parent_dict2(Dictionary)
Traverses a nested dict looking for a particular value. When success is achieved the full key path to the value is printed. I left all the comments and print statements for pedagogical purposes (this isn't production code!)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 24 17:16:46 2022
#author: wellington
"""
class Tree(dict):
"""
allows autovivification as in Perl hashes
"""
def __missing__(self, key):
value = self[key] = type(self)()
return value
# tracking the key sequence when seeking the target
key_list = Tree()
# dict storing the target success result
success = Tree()
# example nested dict of dicts and lists
E = {
'AA':
{
'BB':
{'CC':
{
'DD':
{
'ZZ':'YY',
'WW':'PP'
},
'QQ':
{
'RR':'SS'
},
},
'II':
{
'JJ':'KK'
},
'LL':['MM', 'GG', 'TT']
}
}
}
def find_keys_from_value(data, target):
"""
recursive function -
given a value it returns all the keys in the path to that value within
the dict "data"
there are many paths and many false routes
at the end of a given path if success has not been achieved
the function discards keys to get back to the next possible path junction
"""
print(f"the number of keys in the local dict is {len(data)}")
key_counter = 0
for key in data:
key_counter += 1
# if target has been located stop iterating through keys
if success[target] == 1:
break
else:
# eliminate prior key from path that did not lead to success
if key_counter > 1:
k_list.pop()
# add key to new path
k_list.append(key)
print(f"printing k_list after append{k_list}")
# if target located set success[target] = 1 and exit
if key == target or data[key] == target:
key_list[target] = k_list
success[target] = 1
break
# if the target has not been located check to see if the value
# associated with the new key is a dict and if so return to the
# recursive function with the new dict as "data"
elif isinstance(data[key], dict):
print(f"\nvalue is dict\n {data[key]}")
find_keys_from_value(data[key], target)
# check to see if the value associated with the new key is a list
elif isinstance(data[key], list):
# print("\nv is list\n")
# search through the list
for i in data[key]:
# check to see if the list element is a dict
# and if so return to the recursive function with
# the new dict as "data
if isinstance(i, dict):
find_keys_from_value(i, target)
# check to see if each list element is the target
elif i == target:
print(f"list entry {i} is target")
success[target] = 1
key_list[target] = k_list
elif i != target:
print(f"list entry {i} is not target")
print(f"printing k_list before pop_b {k_list}")
print(f"popping off key_b {key}")
# so if value is not a key and not a list and not the target then
# discard the key from the key list
elif data[key] != target:
print(f"value {data[key]} is not target")
print(f"printing k_list before removing key_before {k_list}")
print(f"removing key_c {key}")
k_list.remove(key)
# select target values
values = ["PP", "SS", "KK", "TT"]
success = {}
for target in values:
print(f"\nlooking for target {target}")
success[target] = 0
k_list = []
find_keys_from_value(E, target)
print(f"\nprinting key_list for target {target}")
print(f"{key_list[target]}\n")
print("\n****************\n\n")
I have result set of rows in a database that all relate to each other through a parent child relationship
Each row is represented as follows objectid, id, parent, child, name, level so when I read an example from the database in my program it looks like this
Organization1
Component1
Department1
Sections1
Sections2
Department2
Sections3
Component2
Department3
Sections4
Sections5
Department4
Sections6
Where Organizations has many departments and departments has many Components and Components has many sections
my code thus far looks like this and that works but I need to put it into json format and the json format has to look like the below
for v in result:
level = v[5]
child = v[3]
parent = v[2]
if level == 0:
OrgDic['InstID'] = v[4]
OrgDic['Child'] = v[3]
OrgDic['Parent'] = v[2]
Organizations.append(InstDic)
OrgDic = {}
if level == 1:
ComponentsDic['CollegeID'] = v[4]
ComponentsDic['Child'] = v[3]
ComponentsDic['Parent'] = v[2]
Components.append(CollegeDic)
ComponentsDic = {}
if level == 2:
DepartmentDic['DepartmentID'] = v[4]
DepartmentDic['Child'] = v[3]
DepartmentDic['Parent'] = v[2]
Departments.append(DepartmentDic)
DepartmentDic = {}
if level == 3:
SectionDic['SubjectID'] = v[4]
SectionDic['Child'] = v[3]
SectionDic['Parent'] = v[2]
Sections.append(SubjectDic)
SectionDic = {}
for w in :
print w['Organization']
for x in Components:
if w['Child'] == x['Parent']:
print x['Components']
for y in Departments:
if x['Child'] == y['Parent']:
print y['Deparments']
for z in Sections:
if y['Child'] == z['Parent']:
print z['Sections']
JSON FORMAT
{
"Eff_Date": "08/02/2013",
"Tree":
[
{
"OrganizationID": "Organization1",
"Components":
[
{"ComponentID": "Component1",
"Departments":
[
{"DepartmentID": "Dep1",
"Sections":
[
{"SectionID": "Section1"},
{"SectionID": "Section2"}
]},
{"DepartmentID": "Dep2",
"Sections":
[
{"SectionID": "Section3"}
]}
]}
]
}
basically, all you have to do is dump the json after your first snippet (given that snippet does correctly create the tree you exposed, I did not thoroughly check it, but it looks coherent):
import json
print json.dumps({"Eff_Date": "08/02/2013", "Tree":Organizations})
and tada!
I was able to do it the following way
data[]
data.append([-1, 0 ,"name1", 0])
data.append([0,1, "name2", 1])
data.append([1, 2, "name3", 1])
data.append([2 ,3, "name4", 2])
data.append([2 ,4, "name5" ,2])
data.append([1 ,5, "name6", 2])
data.append([5, 6, "name7", 3])
data.append([5, 7, "name8",1])
data.append([5, 7, "name9",2])
def listToDict(input):
root = {}
lookup = {}
for parent_id, id, name, attr in input:
if parent_id == -1:
root['name'] = name;
lookup[id] = root
else:
node = {'name': name}
lookup[parent_id].setdefault('children', []).append(node)
lookup[id] = node
return root
result = listToDict(data)
print result
print json.dumps(result)
In my case my data was a result set from a database so I had to loop through it as follows
for v in result:
values = [v[2], v[3], v[4], v[5]]
pc.append(values)